var App = window.App || {};
App.env = "stg";
App.sysCfg = {"ProductManagerGroupId": "1e241c04-81b3-11e4-a225-aa539f25dbda"};
if (location.host == "faadm.superfa.cn") {
    App.env = "prd";
    App.sysCfg.ProductManagerGroupId = "e999f844-81af-11e4-a151-00163e0e2df9"
}
if (App.env == "prd") {
    App.apiHost = "/adminshop/api";
    App.staticHost = "https://www.superfa.cn";
} else {
    App.apiHost = "/adminshop/api";
    App.staticHost = "http://www-stg.superfa.cn";
    window.UEDITOR_CONFIG.imageUrlPrefix = "http://www-stg.superfa.cn";
}

// 优酷视频播放client_id
var YK_CLIENT_ID = 'f8f3c7ce0d32de2d';

App.randomString = function (len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
App.getInt = function (v) {
    return isNaN(v) ? 0 : parseInt(v);
};

App.getFloat = function (v) {
    return isNaN(parseFloat(v)) ? 0 : parseFloat(v);
};

Number.prototype.toFixed = function (exponent) {
    return parseInt(this * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent);
}

App.toFixed = function (num, exponent) {
    return parseInt(num * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent);
}

App.certTypeMap = function () {
    return [{"value": "证劵执业资格", "code": "01"}, {"value": "基金执业资格", "code": "02"}, {
        "value": "期货执业资格",
        "code": "03"
    }, {"value": "黄金投资分析师职业资格", "code": "04"}, {"value": "上海金交所交易员资格", "code": "05"}, {
        "value": "理财规划师职业资格",
        "code": "06"
    }, {"value": "保险咨询", "code": "07"}, {"value": "港股投资咨询", "code": "08"}, {
        "value": "美国证券期货执业资格",
        "code": "09"
    }, {"value": "金融理财师职业资格", "code": "10"}, {"value": "特许金融分析师资格", "code": "11"}, {
        "value": "注册国际投资分析师资格",
        "code": "12"
    }];
};


App.globalSetting = {"tel400": "400-855-8085"};

App.newsTypeMapModel = [ { value:'1',text:"平台信息"}, { value:'2',text:"行业新闻"}, { value:'3',text:"国家政策"}, { value:'4',text:"行业知识"}, { value:'5',text:"法律法规"}, { value:'6',text:"其他"} ];
App.paymentInterestTypeModel = [{value:"01",text:"按月付息"},{value:"02",text:"按季付息"},{value:"03",text:"按半年付息"},{value:"04",text:"按年付息"},{value:"05",text:"到期还本付息"},{value:"06",text:"按自然半年付息"},{value:"07",text:"按顺延半年付息"},{value:"08",text:"按自然季度付息"},{value:"09",text:"按顺延季度付息"}];
App.investTypeModel = [{value:"01",text:"房地产类"},{value:"02",text:"金融市场"},{value:"03",text:"基础设施"},{value:"06",text:"工商企业"},{value:"07",text:"资金池"},{value:"04",text:"其他"}];
App.publicAreaModel = [{value:"01",text:"江浙沪"},{value:"02",text:"京津冀"},{value:"03",text:"珠三角"},{value:"04",text:"其他地区"}];
App.pLevelModel = [{value:"01",text:"AAA"},{value:"02",text:"AA"},{value:"03",text:"A"},{value:"04",text:"BBB"},{value:"05",text:"BB"},{value:"06",text:"B"},{value:"07",text:"CCC"},{value:"08",text:"CC"},{value:"09",text:"C"},{value:"10",text:"D"}];
App.attachmentFileTypeMap = [{value:"image/jpeg",text:"pic"},{value:"image/gif",text:"pic"},{value:"image/png",text:"pic"},{value:"application/pdf",text:"pdf"},{value:"application/octet-stream",text:"word"},{value:"video/x-ms-wmv",text:"vedio"},{value:"video/x-ms-wmv",text:"vedio"},{value:"application/x-tar",text:"rar"},{value:"application/x-gzip",text:"rar"},{value:"application/x-rar-compressed",text:"rar"}];
App.advertPositionModel = [{value:"01",text:"首页顶部轮播",size:"1954x394"},{value:"02",text:"首页底部Banner左",size:"316x100"},{value:"03",text:"首页底部Banner中",size:"316x100"},{value:"04",text:"首页底部Banner右",size:"316x100"},{value:"05",text:"活动右侧Banner",size:"236x190"},{value:"06",text:"首页顶部Banner",size:"1954*80"},{value:"07",text:"注册页面右侧Banner",size:"204x204"},{value:"08",text:"登录页面背景",size:"1954x600"},{value:"09",text:"邮件广告",size:"680x197"},{value:"15", text:"APP Banner", size:"750x300"},{value:"22", text:"APP Banner WAP3.0", size:"750x300"},{value:"16", text:"APP推荐产品1", size:"260x300"},{value:"17", text:"APP推荐产品2", size:"380x145"},{value:"18", text:"APP推荐产品3", size:"190x150"},{value:"19", text:"APP推荐产品4", size:"190x150"}, {value:"20", text:"海外保险-Banner", size:"1024x180"},{value:"21",text:"app首页双图区",size:"170*375"},{value:"23",text:"网站弹窗轮播",size:"750*120"},{value:"24",text:"网站首页媒体热评",size:"277*149"}];
App.productPublicStatusModel = [ { value:'1',text:"未发布"}, { value:'2',text:"已发布"}, { value:'3',text:"已下架"}, { value:'4',text:"原有-审核失败"}];
App.productStatusModel = [ { value:'1',text:"未审核"}, { value:'2',text:"已审核"}, { value:'3',text:"已审核"}, { value:'4',text:"金融产品内部审核中"}, { value:'5',text:"销售发布审核中"}, { value:'6',text:"审核失败"}];
App.productTypeModel = [ { value:'01',text:"私募基金"}, { value:'02',text:"信托"}, { value:'03',text:"资管"},{value:'04',text:'有限合伙'},{value:'06',text:'股权基金'},{value:'07',text:'债权基金'}];

App.dictMap = {
    productStatusMergeModel : [ { value:'1',text:"未审核"}, { value:'2,3',text:"已审核"}, { value:'4',text:"金融产品内部审核中"}, { value:'5',text:"销售发布审核中"}, { value:'6',text:"审核失败"}],
    oDefriendStatusModel : [{ value:'1',text:"正常"}, { value:'2',text:"拉黑"}],
    pEndEarlyIdentification :[{ value:'0',text:"否"}, { value:'1',text:"是"}],
    productCommendWeightModel:[{value:"-1",text:"取消推荐"},{value:"1",text:"一级"},{value:"2",text:"二级"},{value:"3",text:"三级"},{value:"4",text:"四级"},{value:"5",text:"五级"},{value:"6",text:"六级"},{value:"7",text:"七级"},{value:"8",text:"八级"},{value:"9",text:"九级"},{value:"10",text:"十级"},{value:"11",text:"十一级"},{value:"12",text:"十二级"},{value:"13",text:"十三级"}],
    productSaleStatusModel:[ { value:'01',text:"未开始"},{ value:'02',text:"预热中"}, { value:'03',text:"募集中"}, { value:'04',text:"本期募满"},{value:'05',text:'募集结束'}],
    //pevc
    pevcproductSaleStatusModel:[ { value:'01',text:"未开始"},{ value:'02',text:"预热中"},  { value:'03',text:"募集中"}, { value:'04',text:"本期募满"},{value:'05',text:'募集结束'}],
    mediaSourceModel:[{value:'MD', text:'妙点'},{value:'WJT', text:'微讲坛'}, { value:'YQF',text:"亿起发"},{ value:'PT',text:"平台普通注册"},{value : "dsppc",text:"dsppc"},{value : "dspwap",text:"dspwap"},{value : "dspedmwap",text:"dspedmwap"},{value : "adminUserShareReg",text:"内部理财师邀请函"},{value:'SEO',text:'SEO'}],
    actSourceModel:[{ value:'DCWJ',text:"问卷充话费"}, { value:'ZCSHB88',text:"注册送88元红包"}, { value:'SBD300',text:"斯巴达300"},{ value:'cd500',text:"成都组团"},{ value:'XXDR-FX',text:"线下导入-FX"},{ value:'XXDR-0802',text:"线下导入-0802"},{ value:'TXL-20170802',text:"TXL-20170802"},{ value:'NYCF20170803',text:"NYCF20170803"},{ value:'YHDECK20170803',text:"YHDECK20170803"},{ value:'XT20170811',text:"XT20170811"}],
    fissInvestTypeModel : [{value:"01",text:"房地产"},{value:"02",text:"基础设施"},{value:"03",text:"工商企业"},{value:"04",text:"金融市场"},{value:"05",text:"其他"}],
    fissInvestTermModel : [{value:"01",text:"贷款"},{value:"02",text:"股权"},{value:"03",text:"权益投资"},{value:"04",text:"证券投资"},{value:"05",text:"组合投资"},{value:"06",text:"其他"}],
    withdrawStatusModel:[ { value:'01',text:"提现中"},  { value:'02',text:"提现成功"}, { value:'03',text:"提现失败"}],
    bankTypeModel:[ { value:'001',text:"工商银行"},  { value:'002',text:"农业银行"}, { value:'003',text:"建设银行"}, { value:'004',text:"中国银行"},  { value:'005',text:"招商银行"}, { value:'006',text:"交通银行"}, { value:'007',text:"支付宝"},  { value:'008',text:"现金"}],
    userStatusModel:[{ value:'0',text:"正常"}, { value:'1',text:"禁用"},{ value:'2',text:"注销"}],
    zcgbdModel:[{ value:'新进',text:"新进"}, { value:'增仓',text:"增仓"},{ value:'不变',text:"不变"},{ value:'减仓',text:"减仓"}],
    certResultModel:[{ value:'2',text:"认证通过"}, { value:'99',text:"认证不通过"}],
    roleMapModel:[{ value:'1',text:"未提交认证"}, { value:'98',text:"认证审核中"}, { value:'99',text:"认证失败"}, { value:'2',text:"认证通过(个人)"}, { value:'3',text:"认证通过(个人理财用户)"}, { value:'4',text:"认证通过(银行从业者)"}, { value:'5',text:"认证通过(券商和基金从业者)"}, { value:'6',text:"认证通过(第三方从业者)"}, { value:'7',text:"认证通过(信托公司和资管公司从业者)"}, { value:'8',text:"认证通过(房地产经纪人)"}, { value:'9',text:"认证通过(保险从业人员)"},{ value:'10',text:"认证通过(P2P从业者)"}],
    rzMapModel:[{ value:'1',text:"未提交认证"}, { value:'98',text:"认证审核中"},{ value:'99',text:"认证不通过"}, { value:'2',text:"认证通过"}],
    certReasonModel:[{ value:'上传证件与真实情况不符合',text:"上传证件与真实情况不符合"}, { value:'证件类型不符合',text:"证件类型不符合"},{ value:'其它原因',text:"其它原因"}],
    certLevelTypeModel:[{ value:'2',text:"个人"},{ value:'3',text:"个人理财用户"}, { value:'4',text:"银行从业者"},{ value:'5',text:"券商和基金从业者"}, { value:'6',text:"第三方从业者"},{ value:'7',text:"信托公司和资管公司从业者"}, { value:'8',text:"房地产经纪人"}, { value:'9',text:"保险从业人员"},{value:"10",text:"P2P从业者"}],
    simuCompanyTypeModel:[{ value:'民营公司',text:"民营公司"}, { value:'国有企业',text:"国有企业"},{ value:'中外合资企业',text:"中外合资企业"}],
    educationModel:[{ value:'大专',text:"大专"},{ value:'本科',text:"本科"}, { value:'硕士',text:"硕士"},{ value:'博士',text:"博士"}],
    sexModel:[{ value:'男',text:"男"}, { value:'女',text:"女"}],
    simuStatusModel:[{ value:'0',text:"下架"}, { value:'1',text:"上架"}],
    jflModel:[{value:"股票型",text:"股票型"},{value:"多空仓型",text:"多空仓型"},{value:"管理期货",text:"管理期货"},{value:"市场中性",text:"市场中性"},{value:"套利型",text:"套利型"},{value:"宏观策略",text:"宏观策略"},{value:"债券型",text:"债券型"},{value:"货币型",text:"货币型"},{value:"定向增发",text:"定向增发"},{value:"多策略",text:"多策略"},{value:"组合型",text:"组合型"},{value:"海外基金",text:"海外基金"},{value:"其他",text:"其他"}],
    jjflModelNew:[{value:"股票型",text:"股票型"},{value:"债券型",text:"债券型"},{value:"期货型",text:"期货型"},{value:"混合型",text:"混合型"},{value:"其他",text:"其他"}],
    jgxsModel:[{value:"结构性",text:"结构性"},{value:"非结构性",text:"非结构性"}],
    zzxsModel:[{value:"信托",text:"信托"},{value:"券商资管",text:"券商资管"},{value:"有限合伙",text:"有限合伙"},{value:"契约型",text:"契约型"},{value:"基金子公司",text:"基金子公司"},{value:"基金专户",text:"基金专户"},{value:"其他",text:"其他"}],

    pevczzxsModel:[{value:"01",text:"信托"},{value:"02",text:"券商资管"},{value:"03",text:"有限合伙"},{value:"04",text:"契约型基金"},{value:"05",text:"基金子公司"},{value:"06",text:"其他"}],

    jjztModel:[{value:"开放运行",text:"开放运行"},{value:"封闭运行",text:"封闭运行"}],
    simuOrderStatusModel:[{ value:'01',text:"未处理"}, { value:'02',text:"已处理"},{value:'03',text:"已返佣"}],
    millionStatusModel:[{ value:'1',text:"进行中"}, { value:'2',text:"未开始"}, { value:'3',text:"已过期"}],
    millionTypeModel:[{ value:'1',text:"新手专享"}, { value:'2',text:"认证专项"}, { value:'3',text:"不限"}],
    orderStatusModel:[{value:"110",text:"预约中、待审核"},{value:"120",text:"预约中、成交价待审批"},{value:"121",text:"预约中、待审核"},{value:"122",text:"预约中、待审核"},{value:"123",text:"预约中、待审核"},{value:"124",text:"预约中、待审核"},{value:"130",text:"预约成功、待打款"},{value:"140",text:"订单失败"},{value:"210",text:"预约成功、待打款"},{value:"220",text:"已打款、待确认"},{value:"231", text:"申请后端结佣失败"},{value:"240",text:"确认打款、待佣金到账"},{value:"241",text:"申请后端结佣"},{value:"250",text:"确认打款、待佣金到账"},{value:"261",text:"佣金审核通过,待结佣"},{value:"310",text:"佣金到账、待结佣"},{value:"311",text:"佣金到账、待结佣"},{value:"312",text:"佣金到账、待结佣"},{value:"313",text:"佣金到账、待结佣"},{value:"314",text:"佣金到账、待结佣"},{value:"320",text:"已结佣、待确认"},{value:"321",text:"已结佣、待确认"},{value:"330",text:"结佣完成"},{value:"331",text:"结佣完成"},{value:"350",text:"结佣完成"},{value: "360",text:"交易结束"},{value: "361",text:"交易结束"},{value: "888",text:"订单失败"},{value:"999",text:"订单失败"}],
    newOrderStatusModel:[{value:"110",text:"预约中、待审核"},{value:"130",text:"预约成功、待打款"},{value:"140",text:"订单失败"},{value:"210",text:"预约成功、待打款"},{value:"220",text:"已打款、待确认"},{value: "240",text:"等待产品成立"},{value: "250",text:"产品已成立"},{value: "320",text:"已返佣"},{value: "330",text:"反佣已确认"},{value:"999",text:"订单失败"}],
    wechatFlagModel:[{ value:'0',text:"否"}, { value:'1',text:"是"}],
    pSizeRatioTypeModel:[{ value:'01',text:"小额畅打"}, { value:'02',text:"已配出小额"},{ value:'03',text:"严格配比"}, { value:'04',text:"全大额"}],
    orderDefriendStatusModel:[{ value:'1',text:"有效"}, { value:'2',text:"无效"}],
    activitiesCodeModel:[{ value:'BWCFJH',text:"百万财富计划"}, { value:'BWCSY',text:"百万冲十亿"}, { value:'ZXLCSCX',text:"直销理财师促销"}],
    m2bWinTypeModel :[{ value:'01',text:"注册并认证"}, { value:'04',text:"累计1000万"}, { value:'05',text:"累计2000万"},{ value:'06',text:"主推首单100万"},{ value:'07',text:"主推首单300万"},{ value:'08',text:"非主推首单100万"},{ value:'09',text:"非主推首单300万"}],

    messageModuleModel :[{value:"01",text:"产品管理"},{value:"02",text:"用户认证"},{value:"03",text:"交易管理"}],
    messageTitleModel :[{value:"01",text:"注册验证码"},{value:"02",text:"注册发送密码"},{value:"03",text:"审核认证"}],

    adMsgTypeModel : [{value:"1",text:"公司信息"},{value:"2",text:"行业动态"},{value:"3",text:"国家政策"},{value:"4",text:"行业知识"},{value:"5",text:"法律法规"},{value:"6",text:"活动精彩回顾"},{value:"7",text:"其他"},{value:"8",text:"APP最新公告"},{value:"9",text:"APP其他"},{value:"10",text:"早报"}],

    switchModel : [{value:"1",text:"开"},{value:"0",text:"关"}],

    activitiesStatusModel : [{value:"01",text:"上架"},{value:"02",text:"下架"}],
    messageSortModel : [{value:"1",text:"最高"},{value:"2",text:"适中"}],
    recommentTypeModel : [{value:"1",text:"app首页-热销产品"},{value:"2",text:"app首页-最新推荐"}],

    tjzlModel:[{value:"1",text:"三件套"},{value:"5",text:"签字页"},{value:"6",text:"合同封面"},{value:"7",text:"手持签字页与合同封面照"},{value:"8",text:"其它"}],
    tjzlView:[{value:"1",text:"身份证正面"},{value:"5",text:"签字页"},{value:"6",text:"合同封面"},{value:"7",text:"手持签字页与合同封面照"},{value:"8",text:"其它"}],
    newTOrderStatusModel:[{value:"110",text:"预约中、待审核"},{value: "120",text:"成交价待审批"},{value: "130",text:"预约成功"},{value:"140",text:"订单失败"},{value:"210",text:"预约成功、待打款"},{value:"220",text:"已打款、待确认"},{value:"240",text:"确认打款、待佣金到账"},{value: "310",text:"佣金已到账"},{value: "320",text:"财务已结佣"},{value: "330",text:"已确认返佣"}],
    umcompleteOrderStatusModel:[{value:"220",text:"已打款、待确认"},{value:"240",text:"确认打款、待佣金到账"},{value: "310",text:"佣金已到账"},{value: "320",text:"财务已结佣"},{value: "330",text:"已确认返佣"}],
    umcompleteCWOrderStatusModel:[{value: "310",text:"佣金已到账"},{value: "320",text:"财务已结佣"},{value: "330",text:"已确认返佣"}],
    effectiveOrderStatusModel:[{value:"350",text:"结佣完成"},{value: "360",text:"交易结束"}],
    backOrderStatusModel:[{value:"241",text:"确认打款、待佣金到账"},{value: "311",text:"佣金已到账"},{value: "321",text:"财务已结佣"}],
    knotTypeModel:[{value:"01",text:"产品成立结"},{value:"02",text:"到款结"}],
    productSupplierStatusModel:[{value:"0",text:"未提交认证"},{value:"Y",text:"认证已通过"},{value:"2",text:"认证审核中"},{value:"3",text:"认证失败"},{value:"4",text:"认证通过（个人产品提供方）"},{value:"5",text:"认证通过（机构产品提供方）"}],
    productSupplierStatusTypeModel:[{value:"4",text:"个人产品提供方"},{value:"5",text:"机构产品提供方"}],
    outProCheckStatusModel:[{value:"0",text:"待审核"},{value:"1",text:"审核中"},{value:"2",text:"审核通过"},{value:"3",text:"审核不通过"},{value:"4",text:"产品发布"},{value:"5",text:"产品成立"}],
    productRecommendModel: [{value:'10',text:'高佣金'},{value:'11',text:'高收益'},{value:'12',text:'够安全'},{value:'13',text:'期限短'}],
    faUserSex:[{value:"1",text:"男"},{value:"2",text:"女"}],
    faUserCustomerLable:[{ value:'1',text:"信托"},{ value:'2',text:"资管"}, { value:'3',text:"PE/VC"},{ value:'4',text:"阳光私募"}, { value:'5',text:"海外保险"}],
    customerCategoryModel:[{value:"0",text:"未分类客户"},{value:"6",text:"金融行业"},{value:"7",text:"非金融行业"},{value:"8",text:"无效用户(空号)"},{value:"9",text:"联系不上(挂断、停机、无人接听等)"},{value:"5",text:"失效客户"},{ value:"1",text:"**潜在客户(原有)**"}, { value:"2",text:"**普通客户(原有)**"}, { value:"3",text:"**合作伙伴(原有)**"}, { value:"4",text:"**重要客户(原有)**"}],
    customerClickBtnModel:[{"value":"100001","text":"登录"},{"value":"100020","text":"首页banner点击"},{"value":"100030","text":"首页四个推荐产品点击"},{"value":"100040","text":"首页精选产品点击"},{"value":"100050","text":"关于我们"},{"value":"100060","text":"核心团队"},{"value":"100070","text":"合作伙伴"},{"value":"100080","text":"安全保障"},{"value":"100090","text":"加入我们"},{"value":"100100","text":"法律声明"},{"value":"100110","text":"联系我们"},{"value":"100120","text":"帮助中心"},{"value":"100130","text":"信托公司"},{"value":"100000","text":"首页"},{"value":"101000","text":"信托产品"},{"value":"102000","text":"资管计划"},{"value":"103000","text":"PEVC"},{"value":"104000","text":"阳光私募"},{"value":"105000","text":"海外保险"},{"value":"106000","text":"活动相关"},{"value":"101000","text":"信托相关"},{"value":"101010","text":"信托相关-筛选-产品期限-不限"},{"value":"101011","text":"信托相关-筛选-产品期限-6个月以内"},{"value":"101012","text":"信托相关-筛选-产品期限-6至12个月"},{"value":"101013","text":"信托相关-筛选-产品期限-1至2年"},{"value":"101014","text":"信托相关-筛选-产品期限-2年以上"},{"value":"101020","text":"信托相关-筛选-预期收益-不限"},{"value":"101021","text":"信托相关-筛选-预期收益-8%以内"},{"value":"101022","text":"信托相关-筛选-预期收益-8%至10%"},{"value":"101023","text":"信托相关-筛选-预期收益-10%至15%"},{"value":"101024","text":"信托相关-筛选-预期收益-15%以上"},{"value":"101030","text":"信托相关-筛选-付息方式-不限"},{"value":"1010301","text":"信托相关-筛选-付息方式-按月"},{"value":"1010302","text":"信托相关-筛选-付息方式-按季"},{"value":"1010303","text":"信托相关-筛选-付息方式-按半年"},{"value":"1010304","text":"信托相关-筛选-付息方式-按年"},{"value":"1010305","text":"信托相关-筛选-付息方式-到期付本息"},{"value":"101040","text":"信托相关-筛选-投资方向-不限"},{"value":"1010401","text":"信托相关-筛选-投资方向-房地产类"},{"value":"1010402","text":"信托相关-筛选-投资类型-金融市场"},{"value":"1010403","text":"信托相关-筛选-投资类型-基础设施"},{"value":"1010404","text":"信托相关-筛选-投资类型-其他"},{"value":"1010405","text":"信托相关-筛选-投资类型-城投债"},{"value":"1010406","text":"信托相关-筛选-投资类型-工商企业"},{"value":"101050","text":"信托相关-筛选-所在地区-不限"},{"value":"1010501","text":"信托相关-筛选-所在地区-江浙沪"},{"value":"1010502","text":"信托相关-筛选-所在地区-京津翼"},{"value":"1010503","text":"信托相关-筛选-所在地区-珠三角"},{"value":"1010504","text":"信托相关-筛选-所在地区-其他"},{"value":"101060","text":"信托相关-筛选-起购金额-不限"},{"value":"101061","text":"信托相关-筛选-起购金额-50W以上"},{"value":"101062","text":"信托相关-筛选-起购金额-100W以上"},{"value":"101063","text":"信托相关-筛选-起购金额-200W以上"},{"value":"101064","text":"信托相关-筛选-起购金额-300W以上"},{"value":"101070","text":"信托相关-筛选-大小配比-不限"},{"value":"101071","text":"信托相关-筛选-大小配比-小额畅打"},{"value":"101072","text":"信托相关-筛选-大小配比-已配出小额"},{"value":"101073","text":"信托相关-筛选-大小配比-严格配比"},{"value":"101074","text":"信托相关-筛选-大小配比-全大额"},{"value":"101090","text":"信托相关-筛选-募集状态-不限"},{"value":"101091","text":"信托相关-筛选-募集状态-预热中"},{"value":"101092","text":"信托相关-筛选-募集状态-募集中"},{"value":"101093","text":"信托相关-筛选-募集状态-本期募满"},{"value":"101094","text":"信托相关-筛选-募集状态-募集结束"},{"value":"101101","text":"信托相关-点击产品-查看产品详情"},{"value":"101102","text":"信托相关--二维码"},{"value":"101103","text":"信托相关--收藏"},{"value":"101104","text":"信托相关--发送邮件"},{"value":"101105","text":"信托相关--下载"},{"value":"101106","text":"信托相关-详情页-立即预约"},{"value":"102000","text":"资管相关"},{"value":"102010","text":"资管相关-筛选-产品期限-不限"},{"value":"102011","text":"资管相关-筛选-产品期限-6个月以内"},{"value":"102012","text":"资管相关-筛选-产品期限-6至12个月"},{"value":"102013","text":"资管相关-筛选-产品期限-1至2年"},{"value":"102014","text":"资管相关-筛选-产品期限-2年以上"},{"value":"102020","text":"资管相关-筛选-预期收益-不限"},{"value":"102021","text":"资管相关-筛选-预期收益-8%以内"},{"value":"102022","text":"资管相关-筛选-预期收益-8%至10%"},{"value":"102023","text":"资管相关-筛选-预期收益-10%至15%"},{"value":"102024","text":"资管相关-筛选-预期收益-15%以上"},{"value":"102030","text":"资管相关-筛选-付息方式-不限"},{"value":"1020301","text":"资管相关-筛选-付息方式-按月"},{"value":"1020302","text":"资管相关-筛选-付息方式-按季"},{"value":"1020303","text":"资管相关-筛选-付息方式-按半年"},{"value":"1020304","text":"资管相关-筛选-付息方式-按年"},{"value":"1020305","text":"资管相关-筛选-付息方式-到期付本息"},{"value":"102040","text":"资管相关-筛选-投资类型-不限"},{"value":"1020401","text":"资管相关-筛选-投资类型-房地产类"},{"value":"1020402","text":"资管相关-筛选-投资类型-金融市场"},{"value":"1020403","text":"资管相关-筛选-投资类型-基础设施"},{"value":"1020404","text":"资管相关-筛选-投资类型-其他"},{"value":"1020405","text":"资管相关-筛选-投资类型-城投债"},{"value":"1020406","text":"资管相关-筛选-投资类型-工商企业"},{"value":"102050","text":"资管相关-筛选-所在地区-全国"},{"value":"1020501","text":"资管相关-筛选-所在地区-江浙沪"},{"value":"1020502","text":"资管相关-筛选-所在地区-京津翼"},{"value":"1020503","text":"资管相关-筛选-所在地区-珠三角"},{"value":"1020504","text":"资管相关-筛选-所在地区-其他"},{"value":"102060","text":"资管相关-筛选-起购金额-不限"},{"value":"102061","text":"资管相关-筛选-起购金额-50W以上"},{"value":"102062","text":"资管相关-筛选-起购金额-100W以上"},{"value":"102063","text":"资管相关-筛选-起购金额-200W以上"},{"value":"102064","text":"资管相关-筛选-起购金额-300W以上"},{"value":"102070","text":"资管相关-筛选-大小配比-不限"},{"value":"102071","text":"资管相关-筛选-大小配比-小额畅打"},{"value":"102072","text":"资管相关-筛选-大小配比-已配出小额"},{"value":"102073","text":"资管相关-筛选-大小配比-严格配比"},{"value":"102074","text":"资管相关-筛选-大小配比-全大额"},{"value":"102090","text":"资管相关-筛选-募集状态-不限"},{"value":"102091","text":"资管相关-筛选-募集状态-预热中"},{"value":"102092","text":"资管相关-筛选-募集状态-募集中"},{"value":"102093","text":"资管相关-筛选-募集状态-本期募满"},{"value":"102094","text":"资管相关-筛选-募集状态-募集结束"},{"value":"102101","text":"资管相关-点击产品-查看产品详情"},{"value":"102102","text":"资管相关--二维码"},{"value":"102103","text":"资管相关--收藏"},{"value":"102104","text":"资管相关--发送邮件"},{"value":"102105","text":"资管相关--下载"},{"value":"102106","text":"资管相关-详情页-立即预约"},{"value":"103000","text":"PEVC相关"},{"value":"103010","text":"PEVC相关-筛选-起购金额-不限"},{"value":"103011","text":"PEVC相关-筛选-起购金额-100W以上"},{"value":"103012","text":"PEVC相关-筛选-起购金额-300W以上"},{"value":"103013","text":"PEVC相关-筛选-起购金额-500W以上"},{"value":"103014","text":"PEVC相关-筛选-起购金额-1000W以上"},{"value":"103020","text":"PEVC相关-筛选-返佣比例-不限"},{"value":"103021","text":"PEVC相关-筛选-返佣比例-1%以内"},{"value":"103022","text":"PEVC相关-筛选-返佣比例-1%至3%"},{"value":"103023","text":"PEVC相关-筛选-返佣比例-3%以上"},{"value":"103030","text":"PEVC相关-筛选-投资期限-不限"},{"value":"103031","text":"PEVC相关-筛选-投资期限-6个月以内"},{"value":"103032","text":"PEVC相关-筛选-投资期限-6至12个月"},{"value":"103033","text":"PEVC相关-筛选-投资期限-1至2年"},{"value":"103034","text":"PEVC相关-筛选-投资期限-2年以上"},{"value":"103090","text":"PEVC相关-筛选-募集状态-不限"},{"value":"103091","text":"PEVC相关-筛选-募集状态-预热中"},{"value":"103092","text":"PEVC相关-筛选-募集状态-募集中"},{"value":"103093","text":"PEVC相关-筛选-募集状态-本期募满"},{"value":"103094","text":"PEVC相关-筛选-募集状态-募集结束"},{"value":"103101","text":"PEVC相关-点击产品-查看产品详情"},{"value":"103102","text":"PEVC相关--二维码"},{"value":"103103","text":"PEVC相关--收藏"},{"value":"103104","text":"PEVC相关--发送邮件"},{"value":"103105","text":"PEVC相关--下载"},{"value":"103106","text":"PEVC相关-详情页-立即预约"},{"value":"104000","text":"阳光私募相关"},{"value":"104010","text":"阳光私募相关-筛选-投资类型-不限"},{"value":"104011","text":"阳光私募相关-筛选-投资类型-股票型"},{"value":"104012","text":"阳光私募相关-筛选-投资类型-债券型"},{"value":"104013","text":"阳光私募相关-筛选-投资类型-混合型"},{"value":"104014","text":"阳光私募相关-筛选-投资类型-期货型"},{"value":"104015","text":"阳光私募相关-筛选-投资类型-其他"},{"value":"104020","text":"阳光私募相关-筛选-发行方式-不限"},{"value":"104021","text":"阳光私募相关-筛选-发行方式-基金专户"},{"value":"104022","text":"阳光私募相关-筛选-发行方式-券商资管"},{"value":"104023","text":"阳光私募相关-筛选-发行方式-有限公司"},{"value":"104024","text":"阳光私募相关-筛选-发行方式-契约型"},{"value":"104025","text":"阳光私募相关-筛选-发行方式-基金子公司"},{"value":"104026","text":"阳光私募相关-筛选-发行方式-信托"},{"value":"104027","text":"阳光私募相关-筛选-发行方式-其他"},{"value":"104101","text":"阳光私募相关-点击产品-查看产品详情"},{"value":"104106","text":"阳光私募相关-详情页-立即预约"},{"value":"105000","text":"海外保险相关"},{"value":"105101","text":"海外保险相关-点击产品-查看产品详情"},{"value":"105105","text":"海外保险相关--下载"},{"value":"105106","text":"海外保险相关-详情页-立即预约"},{"value":"106000","text":"活动相关"},{"value":"106101","text":"活动相关-点击活动-查看活动详情"},{"value":"106106","text":"活动相关-详情页-立即报名"},{"value":"107000","text":"搜索"},{"value":"199999","text":"退出"}],
    biddingStatusModel : [{"value" : "1","text" : "提交竞价"},{"value" : "2","text" : "竞价失败"},{"value" : "3","text" : "竞价成功"},{"value" : "4","text" : "承销失败"},{"value" : "5","text" : "放弃承销"},{"value" : "6","text" : "收回承销"}],
    fpGroupStatusModel:[{value:"1",text:"已创建"},{value:"2",text:"组团成功结束"},{value:"3",text:"组团失败结束"},{value:"4",text:"组团超时"}],
    payStatusModel:[{value:"paybzj",text:"支付保证金"},{value:"payyj",text:"支付佣金"},{value:"txbzj",text:"提现保证金"},{value:"txyj",text:"提现佣金"}],
    operateTypeModel:[{value:"01",text:"冻结"},{value:"02",text:"未提现"},{value:"03",text:"提现中"},{value:"04",text:"提现成功"},{value:"05",text:"提现失败"},{value:"06",text:"失败"},{value:"07",text:"支付完毕"}],
    newsStatusModel: [{value:"01",text:"未发送"},{value:"02",text:"发送中"},{value:"03",text:"已发送"},{value:"04",text:"发送失败"}],
    tpcComTypeModel: [{value:"1",text:"直销"},{value:"2",text:"渠道"},{value:"3",text:"同类型平台"},{value:"4",text:"信托"},{value:"5",text:"资管"},{value:"6",text:"p2p"},{value:"7",text:"保险"},{value:"8",text:"券商"},{value:"9",text:"银行"}],
    dynamicStateModel: [{value:"01",text:"正常"},{value:"02",text:"活跃"},{value:"03",text:"警告"},{value:"04",text:"拉黑"}],
    blindateSourceModel: [{value:"JRXQ",text:"金融相亲"}],
    blindateUserSexModel: [{value:"1",text:"男"},{value:"2",text:"女"},{value:"3",text:"隐私"}],
//huqy 产品筛选条件
//期限
    dueTimeModel: [{value: "01,02", text: "12个月以内"}, {value: "03", text: "12个月"}, {
        value: "04",
        text: "13-23个月"
    }, {value: "05", text: "24个月"}, {value: "06", text: "24个月以上"}],
    //收益
    annualRevenueModel: [{value: "01", text: "7%以内"}, {value: "02", text: "7%(包含)-8%"}, {
        value: "03",
        text: "8%(包含)-9%"
    }, {value: "04", text: "9%(包含)-10%"}, {value: "05", text: "10%以上"}, {value: "06", text: "浮动"}],
    //起够金额
    minimumAmountModel: [{value: "", text: "不限"}, {value: "500000", text: "50万以上"}, {
        value: "1000000",
        text: "100万以上"
    }, {value: "2000000", text: "200万以上"}, {value: "3000000", text: "300万以上"}],

    //股权起够金额
    gqminimumAmountModel: [{value: "", text: "不限"}, {value: "1000000", text: "100万以上"}, {
        value: "3000000",
        text: "300万以上"
    }, {value: "5000000", text: "500万以上"}, {value: "10000000", text: "1000万以上"}],
    //股权返佣比例
    gqRabateRatioModel: [{value: "", text: "不限"}, {value: "01", text: "1%(不含)以下"}, {
        value: "02",
        text: "1%~3%(不含)"
    }, {value: "03", text: "3%以上"}],
    //股权投资期限
    gqdueTimeModel: [{value: "", text: "不限"}, {value: "01", text: "6个月以内"}, {
        value: "02",
        text: "6~12个月"
    }, {value: "03,04", text: "1~2年"}, {value: "05,06", text: "2年及以上"}],
    //所在地区
    pbelongAreaModel: [{value: "01", text: "北京"}, {value: "02", text: "天津"}, {value: "03", text: "上海"}, {
        value: "04",
        text: "河北"
    }, {value: "05", text: "广东"}, {value: "06", text: "浙江"}, {value: "07", text: "江苏"}, {
        value: "08",
        text: "重庆"
    }, {value: "09", text: "山东"}, {value: "10", text: "福建"}, {value: "11", text: "江西"}, {
        value: "12",
        text: "内蒙古"
    }, {value: "13", text: "辽宁"}, {value: "14", text: "吉林"}, {value: "15", text: "黑龙江"}, {
        value: "16",
        text: "安徽"
    }, {value: "17", text: "山西"}, {value: "18", text: "河南"}, {value: "19", text: "湖北"}, {
        value: "20",
        text: "湖南"
    }, {value: "21", text: "广西"}, {value: "22", text: "海南"}, {value: "23", text: "四川"}, {
        value: "24",
        text: "贵州"
    }, {value: "25", text: "云南"}, {value: "26", text: "西藏"}, {value: "27", text: "陕西"}, {
        value: "28",
        text: "甘肃"
    }, {value: "29", text: "青海"}, {value: "30", text: "宁夏"}, {value: "31", text: "新疆"}, {value: "00", text: "其他"}],

    //新订单列表标题
    orderListTitleModel: [{value: "01", text: "前端订单"}, {value: "02", text: "我的已完成订单"}, {
        value: "03",
        text: "后端订单"
    }, {value: "04", text: "我的失败订单"}, {value: "05", text: "全部前端订单"}, {value: "06", text: "全部已完成订单"}, {
        value: "07",
        text: "全部后端订单"
    }, {value: "08", text: "全部失败订单"}, {value: "09", text: "待审核订单"}],

    //合同状态
    contractStatusModel: [{value: "01", text: "待申请"}, {value: "02", text: "待处理"}, {
        value: "03",
        text: "待寄出"
    }, {value: "04", text: "待回收"}, {value: "05", text: "已回收"}],

    //合同操作按钮状态
    contractStatusMKModel: [{value: "01", text: "申请"}, {value: "02", text: "处理"}, {
        value: "03",
        text: "寄出"
    }, {value: "04", text: "回收"}, {value: "05", text: "查看"}],


    //新订单列表 查询条件key、value
    orderStatusToNameModel: [{value: "all", text: "所有"}, {value: "yyz", text: "预约中"}, {
        value: "dshdd",
        text: "待审核"
    }, {value: "ddk", text: "待打款"}, {value: "qrdkdyjdz", text: "确认打款、待佣金到账 "}, {value: "dqrdk", text: "待确认打款"}, {value: "dqrjy", text: "待结佣"}, {
        value: "qddjy",
        text: "待结佣"
    }, {value: "djy", text: "待结佣"}, {value: "dshhddd", text: "待审核"}, {value: "djyhddd", text: "待结佣"}, {
        value: "hdfydd",
        text: "待结佣"
    }, {value: "hddjy", text: "待结佣"}, {value: "hdjydqr", text: "结佣完成"}, {
        value: "jydqr",
        text: "结佣完成"
    }, {value: "jieywc", text: "结佣成功"}, {value: "wchddd", text: "结佣成功"}, {
        value: "jiaoywc",
        text: "交易完成"
    }, {value: "ddsb", text: "失败订单"}],
    //二次后端结佣类型
    costTypeModel: [{value: "HD_JY", text: "后端结佣"}, {value: "HD_HDFH", text: "后端分红"}, {
        value: "HD_TX",
        text: "贴息"
    }, {value: "HD_SCBT", text: "市场补贴"}, {value: "HD_OTHER", text: "其他"}],
    //后端结佣类型
    costTypeFrontModel: [{value: "HD_JY", text: "后端结佣"}, {value: "HD_SYJK", text: "后端上游结佣"}, {
        value: "QD_SYJK",
        text: "上游结佣"
    }, {value: "QD_JY", text: "前端结佣"}, {value: "QD_CWJY", text: "财务前端结佣"}, {value: "HD_CWJY", text: "后端财务结佣"}],

}

App.filterSimuJson = function (str) {
    str = (str || "") + "";
    str = str.replace(/“/g, '"');
    str = str.replace('{1:{', '{"1":{');
    str = str.replace('},2:{', '},"2":{');
    str = str.replace('},3:{', '},"3":{');
    str = str.replace('},4:{', '},"4":{');
    str = str.replace('},5:{', '},"5":{');
    str = str.replace('},6:{', '},"6":{');
    str = str.replace('},7:{', '},"7":{');
    str = str.replace('},8:{', '},"8":{');

    return str;
};

App.cloneJson = function (o) {
    var t = {}, o = o || {};
    for (var i in o)t[i] = o[i];
    return t;
}

var faApp = angular.module('faApp',['ngRoute','ui.bootstrap','ngCookies','ng.ueditor','moment-picker']);
faApp.config(function($locationProvider,$httpProvider,$sceProvider) {
  $locationProvider.html5Mode(true);
  $httpProvider.defaults.useXDomain  = true;
  $httpProvider.defaults.withCredentials  = true;
  //delete $httpProvider.defaults.headers.common['X-Requested-With'];
  $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

  var param = function(obj) {
    var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

    for(name in obj) {
      value = obj[name];

      if(value instanceof Array) {
        for(i=0; i<value.length; ++i) {
          subValue = value[i];
          fullSubName = name + '[' + i + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value instanceof Object) {
        for(subName in value) {
          subValue = value[subName];
          fullSubName = name + '[' + subName + ']';
          innerObj = {};
          innerObj[fullSubName] = subValue;
          query += param(innerObj) + '&';
        }
      }
      else if(value !== undefined && value !== null)
        query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }

    return query.length ? query.substr(0, query.length - 1) : query;
  };

  // Override $http service's default transformRequest
  $httpProvider.defaults.transformRequest = [function(data) {
    return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
  }];


}) .run(["$rootScope", "$window", "$cookies","$http",function($rootScope,$window,$cookies, $http){
    if(!$cookies.utoken) { }
	$http.defaults.headers.common['Authorization'] = 'FA_'+$cookies.utoken;

    $rootScope.$on('$routeChangeStart', function(evt, absNewUrl, absOldUrl){
        $window.scrollTo(0,0);    //scroll to top of page after each route change
	});
}]);

angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {"DATETIME_FORMATS":{"MONTH":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"SHORTMONTH":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"DAY":["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],"SHORTDAY":["周日","周一","周二","周三","周四","周五","周六"],"AMPMS":["上午","下午"],"medium":"yyyy-M-d ah:mm:ss","short":"yy-M-d ah:mm","fullDate":"y年M月d日EEEE","longDate":"y年M月d日","mediumDate":"yyyy-M-d","shortDate":"yy-M-d","mediumTime":"ah:mm:ss","shortTime":"ah:mm"},"NUMBER_FORMATS":{"DECIMAL_SEP":".","GROUP_SEP":",","PATTERNS":[{"minInt":1,"minFrac":0,"macFrac":0,"posPre":"","posSuf":"","negPre":"-","negSuf":"","gSize":3,"lgSize":3,"maxFrac":3},{"minInt":1,"minFrac":2,"macFrac":0,"posPre":"\u00A4","posSuf":"","negPre":"\u00A4-","negSuf":"","gSize":3,"lgSize":3,"maxFrac":2}],"CURRENCY_SYM":"¥"},"pluralCat":function (n) {  return PLURAL_CATEGORY.OTHER;},"id":"zh-cn"});
}]);

faApp.sysVersion = (new Date()).getTime();
faApp.config(['$routeProvider','$locationProvider',function ($routeProvider, $locationProvider) {
	var v = faApp.sysVersion;
    $routeProvider
      .when('/index', {  templateUrl: 'tpl/index/index.html?' + v,  controller: 'IndexCtrl' })
      .when('/index/panel', {  templateUrl: 'tpl/index/panel.html?' + v,  controller: 'IndexPanelCtrl' })
      //每日展示页
      .when('/index/everyday', {  templateUrl: 'tpl/index/everyday.html?' + v,  controller: 'IndexEverydayCtrl' })
      .when('/login', {  templateUrl: 'tpl/login.html?' + v,  controller: 'LoginCtrl' })
      .when('/logout', {  templateUrl: 'tpl/login.html?' + v,  controller: 'LogoutCtrl' })
      .when('/upinfo', {  templateUrl: 'tpl/upUserInfo.html?' + v,  controller: 'LoginCtrl' })

      .when('/user/list', {  templateUrl: 'tpl/user/list.html?' + v,  controller: 'UserListCtrl' })
      .when('/user/edit', {  templateUrl: 'tpl/user/add.html?' + v,  controller: 'UserEditCtrl' })
      .when('/user/add', {  templateUrl: 'tpl/user/add.html?' + v,  controller: 'UserAddCtrl' })

      .when('/fa/list', {  templateUrl: 'tpl/fa/list.html?' + v,  controller: 'FaListCtrl' })
      .when('/fa/edit', {  templateUrl: 'tpl/fa/edit.html?' + v,  controller: 'FaEditCtrl' })
      .when('/fa/view', {  templateUrl: 'tpl/fa/view.html?' + v,  controller: 'FaViewCtrl' })
      .when('/fa/blacklist', {  templateUrl: 'tpl/fa/blacklist.html?' + v,  controller: 'FaBlackListCtrl' })
      .when('/fa/blackview', {  templateUrl: 'tpl/fa/blackview.html?' + v,  controller: 'FaBlackViewCtrl' })
      .when('/fa/sbdstat', {  templateUrl: 'tpl/fa/sbdstat.html?' + v,  controller: 'FaSbdstatCtrl' })
      .when('/fa/sbddetail', {  templateUrl: 'tpl/fa/sbddetail.html?' + v,  controller: 'FaSbdDetailCtrl' })

      .when('/ad/list', {  templateUrl: 'tpl/ad/list.html?' + v,  controller: 'AdListCtrl' })
      .when('/ad/add', {  templateUrl: 'tpl/ad/add.html?' + v,  controller: 'AdAddCtrl' })
      .when('/ad/edit', {  templateUrl: 'tpl/ad/edit.html?' + v,  controller: 'AdEditCtrl' })

      .when('/link/list', {  templateUrl: 'tpl/link/list.html?' + v,  controller: 'LinkListCtrl' })
      .when('/link/add', {  templateUrl: 'tpl/link/add.html?' + v,  controller: 'LinkAddCtrl' })
      .when('/link/edit', {  templateUrl: 'tpl/link/edit.html?' + v,  controller: 'LinkEditCtrl' })

      .when('/product/list', {  templateUrl: 'tpl/product/list.html?' + v,  controller: 'ProductListCtrl' })
      .when('/product/add', {  templateUrl: 'tpl/product/base.html?' + v,  controller: 'ProductAddCtrl' })
      .when('/product/edit', {  templateUrl: 'tpl/product/add.html?' + v,  controller: 'ProductEditCtrl' })
      .when('/product/base', {  templateUrl: 'tpl/product/base.html?' + v,  controller: 'ProductBaseInfoCtrl' })
      .when('/product/view', {  templateUrl: 'tpl/product/view.html?' + v,  controller: 'ProductViewCtrl' })
      .when('/product/saleProcess', {  templateUrl: 'tpl/product/saleProcess.html?' + v,  controller: 'ProductSaleProcessCtrl' })
      .when('/product/profit', {  templateUrl: 'tpl/product/profit.html?' + v,  controller: 'ProductProfitCtrl' })
      .when('/product/attach', {  templateUrl: 'tpl/product/attach.html?' + v,  controller: 'ProductAttachCtrl' })
      .when('/product/video', {  templateUrl: 'tpl/product/video.html?' + v,  controller: 'ProductVideoCtrl' })
      .when('/product/pronoticeattach', {  templateUrl: 'tpl/product/productNoticeFile.html?' + v,  controller: 'ProductNoiceCtrl' })

      .when('/productnotice/base', {  templateUrl: 'tpl/product/productNoticeBase.html?' + v,  controller: 'ProductNoticeBaseCtrl' })
      .when('/productnotice/list', {  templateUrl: 'tpl/product/productNoticeList.html?' + v,  controller: 'ProductNoticeListCtrl' })
      .when('/productnotice/edit', {  templateUrl: 'tpl/product/productNoticeEdit.html?' + v,  controller: 'ProductNoticeEditCtrl' })
      .when('/productnotice/detail', {  templateUrl: 'tpl/product/productNoticeDetail.html?' + v,  controller: 'ProductNoticeDetailCtrl' })

      .when('/pevcproduct/list', {  templateUrl: 'tpl/pevcproduct/list.html?' + v,  controller: 'PEVCProductListCtrl' })
      .when('/pevcproduct/add', {  templateUrl: 'tpl/pevcproduct/add.html?' + v,  controller: 'PEVCProductAddCtrl' })
      .when('/pevcproduct/edit', {  templateUrl: 'tpl/pevcproduct/base.html?' + v,  controller: 'PEVCProductEditCtrl' })
      .when('/pevcproduct/view', {  templateUrl: 'tpl/pevcproduct/view.html?' + v,  controller: 'PEVCProductViewCtrl' })
      .when('/pevcproduct/baseInfo', {  templateUrl: 'tpl/pevcproduct/add.html?' + v,  controller: 'PEVCProductBaseInfoCtrl' })
      .when('/pevcproduct/saleProcess', {  templateUrl: 'tpl/pevcproduct/saleProcess.html?' + v,  controller: 'PEVCProductSaleProcessCtrl' })
      .when('/company/list', {  templateUrl: 'tpl/company/list.html?' + v,  controller: 'CompanyListCtrl' })
      .when('/company/add', {  templateUrl: 'tpl/company/add.html?' + v,  controller: 'CompanyAddCtrl' })
      .when('/company/edit', {  templateUrl: 'tpl/company/add.html?' + v,  controller: 'CompanyEditCtrl' })
      .when('/company/view', {  templateUrl: 'tpl/company/view.html?' + v,  controller: 'CompanyViewCtrl' })
      .when('/company/sub', {  templateUrl: 'tpl/company/sub.html?' + v,  controller: 'CompanySubCtrl' })

      .when('/role/list', {  templateUrl: 'tpl/auth/listRole.html?' + v,  controller: 'RoleListCtrl' })
      .when('/role/add', {  templateUrl: 'tpl/auth/addRole.html?' + v,  controller: 'RoleAddCtrl' })
      .when('/role/edit', {  templateUrl: 'tpl/auth/addRole.html?' + v,  controller: 'RoleEditCtrl' })
      .when('/url/list', {  templateUrl: 'tpl/auth/listUrl.html?' + v,  controller: 'UrlListCtrl' })
      .when('/url/add', {  templateUrl: 'tpl/auth/addUrl.html?' + v,  controller: 'UrlAddCtrl' })

      .when('/withdraw/list', {  templateUrl: 'tpl/withdraw/list.html?' + v,  controller: 'WithdrawListCtrl' })
      .when('/withdraw/view', {  templateUrl: 'tpl/withdraw/view.html?' + v,  controller: 'WithdrawViewCtrl' })

      .when('/info/fiss', {  templateUrl: 'tpl/info/fiss/list.html?' + v,  controller: 'FissListCtrl' })
      .when('/info/fiss/view', {  templateUrl: 'tpl/info/fiss/view.html?' + v,  controller: 'FissViewCtrl' })

      .when('/simu/list', {  templateUrl: 'tpl/simu/list.html?' + v,  controller: 'SimuListCtrl' })
      .when('/simu/add', {  templateUrl: 'tpl/simu/add.html?' + v,  controller: 'SimuAddCtrl' })
      .when('/simu/edit', {  templateUrl: 'tpl/simu/add.html?' + v,  controller: 'SimuEditCtrl' })
      .when('/simu/view', {  templateUrl: 'tpl/simu/view.html?' + v,  controller: 'SimuViewCtrl' })
      .when('/simu/baseinfo', {  templateUrl: 'tpl/simu/baseinfo.html?' + v,  controller: 'SimuBaseInfoCtrl' })
      .when('/simu/manager/list', {  templateUrl: 'tpl/simu/manager/list.html?' + v,  controller: 'SimuManagerListCtrl' })
      .when('/simu/manager/add', {  templateUrl: 'tpl/simu/manager/add.html?' + v,  controller: 'SimuManagerAddCtrl' })
      .when('/simu/manager/edit', {  templateUrl: 'tpl/simu/manager/add.html?' + v,  controller: 'SimuManagerEditCtrl' })
      .when('/simu/manager/view', {  templateUrl: 'tpl/simu/manager/view.html?' + v,  controller: 'SimuManagerViewCtrl' })
      .when('/simu/company/list', {  templateUrl: 'tpl/simu/company/list.html?' + v,  controller: 'SimuCompanyListCtrl' })
      .when('/simu/company/add', {  templateUrl: 'tpl/simu/company/add.html?' + v,  controller: 'SimuCompanyAddCtrl' })
      .when('/simu/company/edit', {  templateUrl: 'tpl/simu/company/add.html?' + v,  controller: 'SimuCompanyEditCtrl' })
      .when('/simu/company/view', {  templateUrl: 'tpl/simu/company/view.html?' + v,  controller: 'SimuCompanyViewCtrl' })
      .when('/simu/buyinfo/list', {  templateUrl: 'tpl/simu/buyinfo/list.html?' + v,  controller: 'SimuBuyInfoListCtrl' })
      .when('/simu/buyinfo/add', {  templateUrl: 'tpl/simu/buyinfo/add.html?' + v,  controller: 'SimuBuyInfoAddCtrl' })
      .when('/simu/buyinfo/edit', {  templateUrl: 'tpl/simu/buyinfo/add.html?' + v,  controller: 'SimuBuyInfoEditCtrl' })
      .when('/simu/buyinfo/view', {  templateUrl: 'tpl/simu/buyinfo/view.html?' + v,  controller: 'SimuBuyInfoViewCtrl' })
      .when('/simu/buyhis/list', {  templateUrl: 'tpl/simu/buyhis/list.html?' + v,  controller: 'SimuBuyHisListCtrl' })
      .when('/simu/buyhis/add', {  templateUrl: 'tpl/simu/buyhis/add.html?' + v,  controller: 'SimuBuyHisAddCtrl' })
      .when('/simu/buyhis/edit', {  templateUrl: 'tpl/simu/buyhis/add.html?' + v,  controller: 'SimuBuyHisEditCtrl' })
      .when('/simu/buyhis/view', {  templateUrl: 'tpl/simu/buyhis/view.html?' + v,  controller: 'SimuBuyHisViewCtrl' })
      .when('/simu/buyhis/addlist', {  templateUrl: 'tpl/simu/buyhis/addlist.html?' + v,  controller: 'SimuBuyHisNewCtrl' })
      .when('/simu/lsyj', {  templateUrl: 'tpl/simu/lsyj.html?' + v,  controller: 'SimuLsyjCtrl' })
      .when('/simu/ndyj', {  templateUrl: 'tpl/simu/ndyj.html?' + v,  controller: 'SimuNdyjCtrl' })
      .when('/simu/lsjz', {  templateUrl: 'tpl/simu/lsjz.html?' + v,  controller: 'SimuLsjzCtrl' })
      .when('/simu/spnr', {  templateUrl: 'tpl/simu/spnr.html?' + v,  controller: 'SimuSpnrCtrl' })
      .when('/simu/order/list', {  templateUrl: 'tpl/simu/order/list.html?' + v,  controller: 'SimuOrderListCtrl' })
      .when('/simu/order/view', {  templateUrl: 'tpl/simu/order/view.html?' + v,  controller: 'SimuOrderViewCtrl' })

      .when('/simu/order/phoUpload',{templateUrl: 'tpl/simu/order/orderPhoUpload.html?' + v,  controller: 'OrderPhoUploadCtrl'})
      .when('/productOrderData/list', {  templateUrl: 'tpl/productOrderData/list.html?' + v,  controller: 'ProductOrderDataCtrl' })
      .when('/productOrderData/edit',{ templateUrl: 'tpl/productOrderData/edit.html?' + v,  controller: 'editProductOrderDataCtrl' })

      .when('/million/list', {  templateUrl: 'tpl/million/list.html?' + v,  controller: 'MillionListCtrl' })
      .when('/million/add', {  templateUrl: 'tpl/million/add.html?' + v,  controller: 'MillionAddCtrl' })
      .when('/million/edit', {  templateUrl: 'tpl/million/add.html?' + v,  controller: 'MillionEditCtrl' })

      .when('/activity/add', {  templateUrl: 'tpl/activity/add.html?' + v,  controller: 'ActivityAddCtrl' })
      .when('/activity/list', {  templateUrl: 'tpl/activity/list.html?' + v,  controller: 'ActivityListCtrl' })
      .when('/activity/add/product', {  templateUrl: 'tpl/activity/product.html?' + v,  controller: 'ActivityAddProductCtrl' })


      .when('/order/list', {  templateUrl: 'tpl/order/list.html?' + v,  controller: 'OrderListCtrl' })
      .when('/order/view', {  templateUrl: 'tpl/order/view.html?' + v,  controller: 'OrderViewCtrl' })
      .when('/order/phoUpload', {  templateUrl: 'tpl/order/orderPhoUpload.html?' + v,  controller: 'OrderPEVCPhoUploadCtrl' })

      .when('/pevcorder/list', {  templateUrl: 'tpl/order/list.html?' + v,  controller: 'PEVCOrderListCtrl' })

      .when('/tools/upload', {  templateUrl: 'tpl/tools/upload.html?' + v,  controller: 'ToolsUploadCtrl' })

      .when('/m2b/list', {  templateUrl: 'tpl/m2b/list.html?' + v,  controller: 'M2bWinListCtrl' })

      .when('/supplier/list', {  templateUrl: 'tpl/supplier/list.html?' + v,  controller: 'SupplierListCtrl' })
      .when('/supplier/flow', {  templateUrl: 'tpl/supplier/flow.html?' + v,  controller: 'SupplierFlowListCtrl' })
      .when('/supplier/add', {  templateUrl: 'tpl/supplier/add.html?' + v,  controller: 'SupplierAddCtrl' })
      .when('/supplier/edit', {  templateUrl: 'tpl/supplier/add.html?' + v,  controller: 'SupplierEditCtrl' })

      .when('/report/base', {  templateUrl: 'tpl/report/base.html?' + v,  controller: 'ReportBaseCtrl' })
      .when('/report/xmgy', {  templateUrl: 'tpl/report/xmgy.html?' + v,  controller: 'ReportXmgyCtrl' })
      .when('/report/jgt', {  templateUrl: 'tpl/report/jgt.html?' + v,  controller: 'ReportJgtCtrl' })
      .when('/report/hkly', {  templateUrl: 'tpl/report/hkly.html?' + v,  controller: 'ReportHklyCtrl' })
      .when('/report/zjyt', {  templateUrl: 'tpl/report/zjyt.html?' + v,  controller: 'ReportZjytCtrl' })
      .when('/report/fkcs', {  templateUrl: 'tpl/report/fkcs.html?' + v,  controller: 'ReportFkcsCtrl' })
      .when('/report/rzf', {  templateUrl: 'tpl/report/rzf.html?' + v,  controller: 'ReportRzfCtrl' })
      .when('/report/fxf', {  templateUrl: 'tpl/report/fxf.html?' + v,  controller: 'ReportFxfCtrl' })
      .when('/report/xgzl', {  templateUrl: 'tpl/report/xgzl.html?' + v,  controller: 'ReportXgzlCtrl' })

      .when('/statistical/order', { templateUrl: 'tpl/statistical/order.html?' + v, controller: 'StatisticalOrderCtrl'})
      .when('/statistical/user', { templateUrl: 'tpl/statistical/user.html?' + v, controller: 'StatisticalUserCtrl'})

      .when('/message/list', { templateUrl: 'tpl/message/list.html?' + v, controller: 'MessageListCtrl'})
      .when('/message/edit', { templateUrl: 'tpl/message/add.html?' + v, controller: 'MessageEditCtrl'})

      .when('/ad/msg-list', { templateUrl: 'tpl/ad/msgList.html?' + v, controller: 'MsgListCtrl'})
      .when('/ad/msg-add', { templateUrl: 'tpl/ad/msgAdd.html?' + v, controller: 'MsgAddCtrl'})
      .when('/ad/msg-update', { templateUrl: 'tpl/ad/msgAdd.html?' + v, controller: 'MsgUpdateCtrl'})

      .when('/ad/act-list', { templateUrl: 'tpl/ad/actList.html?' + v, controller: 'ActListCtrl'})
      .when('/ad/act-add', { templateUrl: 'tpl/ad/actAdd.html?' + v, controller: 'ActAddCtrl'})
      .when('/ad/act-update', { templateUrl: 'tpl/ad/actAdd.html?' + v, controller: 'ActUpdateCtrl'})

      .when('/im/fb/list', { templateUrl: 'tpl/infoManage/feedBack/list.html?' + v, controller: 'InfoManageFeedBackCtrl'})
      .when('/im/bc/list', { templateUrl: 'tpl/finance/bankCard/list.html?' + v, controller: 'InfoManageBankCardCtrl'})
      .when('/im/withdraw/list', { templateUrl: 'tpl/finance/withdraw/list.html?' + v, controller: 'InfoManageWithdrawCtrl'})
      .when('/im/withdraw/detail', { templateUrl: 'tpl/finance/withdraw/detail.html?' + v, controller: 'InfoManageWithdrawDetailCtrl'})
      .when('/im/payRunning/list', { templateUrl: 'tpl/finance/payRunning/list.html?' + v, controller: 'InfoManageWithPayRunningCtrl'})
      .when('/im/drawAskFor/list', { templateUrl: 'tpl/finance/drawAskFor/list.html?' + v, controller: 'InfoManageWithDrawAskForCtrl'})
      .when('/im/drawAskFor/detail', { templateUrl: 'tpl/finance/drawAskFor/detail.html?' + v, controller: 'InfoManageWithDrawAskForDetailCtrl'})

      //
      .when('/finance/fpAccountVoucher/list', { templateUrl: 'tpl/finance/fpAccountVoucher/list.html?' + v, controller: 'FpAccountVoucherCtrl'})
      .when('/finance/fpAccountVoucher/add', { templateUrl: 'tpl/finance/fpAccountVoucher/add.html?' + v, controller: 'FpAccountVoucherDetailCtrl'})

      .when('/switch/list', { templateUrl: 'tpl/switch/list.html?' + v, controller: 'SwitchListCtrl'})
      .when('/setting/list', { templateUrl: 'tpl/setting/list.html?' + v, controller: 'SettingListCtrl'})

      .when('/order/manager/user/list', { templateUrl: 'tpl/order/manager/user/list.html?' + v, controller: 'OrderManagerUserListCtrl'})
      .when('/order/manager/user/add', { templateUrl: 'tpl/order/manager/user/add.html?' + v, controller: 'OrderManagerUserAddCtrl'})

      .when('/system/403', {  templateUrl: 'tpl/system/403.html?' + v,  controller: 'System403Ctrl' })
      .when('/order/followUp/list', {  templateUrl: 'tpl/order/manager/followUp/list.html?' + v,  controller: 'OrderFollowUpListCtrl' })
      .when('/order/followUp/simu/list', {  templateUrl: 'tpl/order/manager/followUp/simu/list.html?' + v,  controller: 'FollowUpCtrl' })

      .when('/neworder/qudao/myorder/incomplete/list', {  templateUrl: 'tpl/neworder/qudao/myorder/incomplete/list.html?' + v,  controller: 'NewOrderQDMListCtrl' })
      .when('/neworder/qudao/myorder/incomplete/view', {  templateUrl: 'tpl/neworder/qudao/myorder/incomplete/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/myorder/effective/list', {  templateUrl: 'tpl/neworder/qudao/myorder/effective/list.html?' + v,  controller: 'NewOrderQDMListCtrl' })
      .when('/neworder/qudao/myorder/effective/view', {  templateUrl: 'tpl/neworder/qudao/myorder/effective/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/myorder/back/list', {  templateUrl: 'tpl/neworder/qudao/myorder/back/list.html?' + v,  controller: 'NewOrderQDMListCtrl' })
      .when('/neworder/qudao/myorder/back/view', {  templateUrl: 'tpl/neworder/qudao/myorder/back/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/myorder/cancle/list', {  templateUrl: 'tpl/neworder/qudao/myorder/cancle/list.html?' + v,  controller: 'NewOrderQDMListCtrl' })
      .when('/neworder/qudao/myorder/cancle/view', {  templateUrl: 'tpl/neworder/qudao/myorder/cancle/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })

      .when('/neworder/qudao/ordermanager/incomplete/list', {  templateUrl: 'tpl/neworder/qudao/ordermanager/incomplete/list.html?' + v,  controller: 'NewOrderQDAListCtrl' })
      .when('/neworder/qudao/ordermanager/incomplete/view', {  templateUrl: 'tpl/neworder/qudao/ordermanager/incomplete/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/ordermanager/effective/list', {  templateUrl: 'tpl/neworder/qudao/ordermanager/effective/list.html?' + v,  controller: 'NewOrderQDAListCtrl' })
      .when('/neworder/qudao/ordermanager/effective/view', {  templateUrl: 'tpl/neworder/qudao/ordermanager/effective/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/ordermanager/back/list', {  templateUrl: 'tpl/neworder/qudao/ordermanager/back/list.html?' + v,  controller: 'NewOrderQDAListCtrl' })
      .when('/neworder/qudao/ordermanager/back/view', {  templateUrl: 'tpl/neworder/qudao/ordermanager/back/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/qudao/ordermanager/cancle/list', {  templateUrl: 'tpl/neworder/qudao/ordermanager/cancle/list.html?' + v,  controller: 'NewOrderQDAListCtrl' })
      .when('/neworder/qudao/ordermanager/cancle/view', {  templateUrl: 'tpl/neworder/qudao/ordermanager/cancle/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })

      .when('/neworder/chanping/myorder/incomplete/list', {  templateUrl: 'tpl/neworder/chanping/myorder/incomplete/list.html?' + v,  controller: 'NewOrderCPMListCtrl' })
      .when('/neworder/chanping/myorder/incomplete/view', {  templateUrl: 'tpl/neworder/chanping/myorder/incomplete/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/myorder/effective/list', {  templateUrl: 'tpl/neworder/chanping/myorder/effective/list.html?' + v,  controller: 'NewOrderCPMListCtrl' })
      .when('/neworder/chanping/myorder/effective/view', {  templateUrl: 'tpl/neworder/chanping/myorder/effective/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/myorder/audit/list', {  templateUrl: 'tpl/neworder/chanping/myorder/audit/list.html?' + v,  controller: 'NewOrderCPMListCtrl' })
      .when('/neworder/chanping/myorder/audit/view', {  templateUrl: 'tpl/neworder/chanping/myorder/audit/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/myorder/back/list', {  templateUrl: 'tpl/neworder/chanping/myorder/back/list.html?' + v,  controller: 'NewOrderCPMListCtrl' })
      .when('/neworder/chanping/myorder/back/view', {  templateUrl: 'tpl/neworder/chanping/myorder/back/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/myorder/cancle/list', {  templateUrl: 'tpl/neworder/chanping/myorder/failure/list.html?' + v,  controller: 'NewOrderCPMListCtrl' })
      .when('/neworder/chanping/myorder/cancle/view', {  templateUrl: 'tpl/neworder/chanping/myorder/failure/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })

      .when('/neworder/chanping/ordermanager/incomplete/list', {  templateUrl: 'tpl/neworder/chanping/ordermanager/incomplete/list.html?' + v,  controller: 'NewOrderCPAListCtrl' })
      .when('/neworder/chanping/ordermanager/incomplete/view', {  templateUrl: 'tpl/neworder/chanping/ordermanager/incomplete/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/ordermanager/effective/list', {  templateUrl: 'tpl/neworder/chanping/ordermanager/effective/list.html?' + v,  controller: 'NewOrderCPAListCtrl' })
      .when('/neworder/chanping/ordermanager/effective/view', {  templateUrl: 'tpl/neworder/chanping/ordermanager/effective/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/ordermanager/audit/list', {  templateUrl: 'tpl/neworder/chanping/ordermanager/audit/list.html?' + v,  controller: 'NewOrderCPAListCtrl' })
      .when('/neworder/chanping/ordermanager/audit/view', {  templateUrl: 'tpl/neworder/chanping/ordermanager/audit/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/ordermanager/back/list', {  templateUrl: 'tpl/neworder/chanping/ordermanager/back/list.html?' + v,  controller: 'NewOrderCPAListCtrl' })
      .when('/neworder/chanping/ordermanager/back/view', {  templateUrl: 'tpl/neworder/chanping/ordermanager/back/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/chanping/ordermanager/cancle/list', {  templateUrl: 'tpl/neworder/chanping/ordermanager/failure/list.html?' + v,  controller: 'NewOrderCPAListCtrl' })
      .when('/neworder/chanping/ordermanager/cancle/view', {  templateUrl: 'tpl/neworder/chanping/ordermanager/failure/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })

      .when('/neworder/caiwu/ordermanager/incomplete/list', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/incomplete/list.html?' + v,  controller: 'NewOrderCWAListCtrl' })
      .when('/neworder/caiwu/ordermanager/incomplete/view', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/incomplete/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/caiwu/ordermanager/effective/list', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/effective/list.html?' + v,  controller: 'NewOrderCWAListCtrl' })
      .when('/neworder/caiwu/ordermanager/effective/view', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/effective/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })
      .when('/neworder/caiwu/ordermanager/back/list', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/back/list.html?' + v,  controller: 'NewOrderCWAListCtrl' })
      .when('/neworder/caiwu/ordermanager/back/view', {  templateUrl: 'tpl/neworder/caiwu/ordermanager/back/view.html?' + v,  controller: 'NewOrderQDViewCtrl' })

      // 合并订单列表页和ctr
      .when('/neworder/neworder0815/list', {  templateUrl: 'tpl/neworder/neworder0815/list.html?' + v,  controller: 'NewOrderListGZCtrl' })
      .when('/neworder/neworder0815/view', {  templateUrl: 'tpl/neworder/neworder0815/view.html?' + v,  controller: 'NewOrderViewCtrl' })
      .when('/neworder/neworder0815/base', {  templateUrl: 'tpl/neworder/neworder0815/base.html?' + v,  controller: 'NewOrderBaseCtrl' })
      //合同
      .when('/neworder/neworder0815/contract/view', {  templateUrl: 'tpl/neworder/neworder0815/contract/view.html?' + v,  controller: 'OrderContractCtrl' })

      .when('/product/qudaoList', {  templateUrl: 'tpl/product/qudaoList.html?' + v,  controller: 'ProductQDListCtrl' })
      .when('/product/qudaoView', {  templateUrl: 'tpl/product/qudaoView.html?' + v,  controller: 'ProductQDViewCtrl' })
      .when('/product/qudaoListResult', {  templateUrl: 'tpl/product/qudaoListResult.html?' + v,  controller: 'ProductQDListCtrl' })


      .when('/finance/order/list', {  templateUrl: 'tpl/finance/order/list.html?' + v,  controller: 'NewOrderCWGLYListCtrl' })
      .when('/finance/product/view', {  templateUrl: 'tpl/finance/product/view.html?' + v,  controller: 'NewOrderCWAViewCtrl' })

      //理财师管理
      .when('/fa/manager/list', { templateUrl: 'tpl/fa/manager/list.html?' + v, controller: 'LicaishiManagerUserListCtrl'})
      .when('/fa/manager/add', { templateUrl: 'tpl/fa/manager/add.html?' + v, controller: 'LicaishiManagerUserAddCtrl'})


      .when('/outproduct/list', { templateUrl: 'tpl/outProduct/list.html?' + v, controller: 'OutProductListCtrl'})
      .when('/outproduct/detail', { templateUrl: 'tpl/outProduct/detail.html?' + v, controller: 'OutProductDetailCtrl'})
      .when('/personalsupplier/list', { templateUrl: 'tpl/personalsupplier/list.html?' + v, controller: 'PersonalSupplierListCtrl'})
      .when('/personalsupplier/detail', { templateUrl: 'tpl/personalsupplier/detail.html?' + v, controller: 'PersonalSupplierDetailCtrl'})
      .when('/personalsupplier/detail', { templateUrl: 'tpl/personalsupplier/detail.html?' + v, controller: 'PersonalSupplierDetailCtrl'})

      .when('/varietyProduct/list', { templateUrl: 'tpl/varietyProduct/list.html?' + v, controller: 'VarietyProductListCtrl'})
      .when('/varietyProduct/detail', { templateUrl: 'tpl/varietyProduct/detail.html?' + v, controller: 'NewProductDetailCtrl'})
      .when('/varietyProduct/samePro', { templateUrl: 'tpl/varietyProduct/samePro.html?' + v, controller: 'SameProductListCtrl'})
      // .when('/varietyProduct/likePro', { templateUrl: 'tpl/varietyProduct/likePro.html?' + v, controller: 'LikeProductListCtrl'})
      .when('/varietyProduct/newPro', { templateUrl: 'tpl/varietyProduct/newPro.html?' + v, controller: 'NewProductListCtrl'})
      .when('/varietyProduct/adjust', { templateUrl: 'tpl/varietyProduct/adjust.html?' + v, controller: 'ProductAddCtrl'})
      .when('/varietyProduct/sameProDetail', { templateUrl: 'tpl/varietyProduct/sameProDetail.html?' + v, controller: 'SameProductDetailCtrl'})
      .when('/varietyProduct/add', { templateUrl: 'tpl/varietyProduct/base.html?' + v, controller: 'addsNewProductCtrl'})
      //壹财富xpath配置
       .when('/productRegex/list', { templateUrl: 'tpl/productRegex/list.html?' + v, controller: 'ProductRegexCtrl'})

      .when('/bidproduct/list', { templateUrl: 'tpl/bidproduct/list.html?' + v, controller: 'BidProductListCtrl'})
      .when('/bidproduct/detail', { templateUrl: 'tpl/bidproduct/detail.html?'+v,controller:'BidProductDetailCtrl'})



      .when('/system/403', {  templateUrl: 'tpl/system/403.html?' + v,  controller: 'System403Ctrl' })
      .when('/order/followUp/list', {  templateUrl: 'tpl/order/manager/followUp/list.html?' + v,  controller: 'OrderFollowUpListCtrl' })
      .when('/order/followUp/simu/list', {  templateUrl: 'tpl/order/manager/followUp/simu/list.html?' + v,  controller: 'FollowUpCtrl' })

      .when('/chooseRecommend/list', {  templateUrl: 'tpl/product/recommend/list.html?' + v,  controller: 'ProductChooseRecommendList' })
      .when('/chooseRecommend/add', {  templateUrl: 'tpl/product/recommend/add.html?' + v,  controller: 'ProductChooseRecommendAdd' })
      .when('/chooseRecommend/edit', {  templateUrl: 'tpl/product/recommend/add.html?' + v,  controller: 'ProductChooseRecommendEdit' })

      .when('/super/list', {  templateUrl: 'tpl/ad/super/list.html?' + v,  controller: 'AdSuperList' })
      .when('/super/add', {  templateUrl: 'tpl/ad/super/add.html?' + v,  controller: 'AdSuperAdd' })
      .when('/super/edit', {  templateUrl: 'tpl/ad/super/add.html?' + v,  controller: 'AdSuperEdit' })

      .when('/mediaRecommend/list', {  templateUrl: 'tpl/media/recommend/list.html?' + v,  controller: 'MediaRecommendListCtrl' })

      .when('/behavior/list', {  templateUrl: 'tpl/behavior/list.html?' + v, controller:'BehaviorCtrl' })
      .when('/behavior/view',{ templateUrl:'tpl/behavior/view.html?' + v,controller:'BehaviorViewCtrl' })

      .when('/salecon/list',{ templateUrl: 'tpl/salecon/list.html?' + v, controller:'SaleconListCtrl' })

      .when('/product/hot', {  templateUrl: 'tpl/product/other/hot.html?' + v,  controller: 'ProductHotCtrl' })


      .when('/hongbao/list', {  templateUrl: 'tpl/hongbao/list.html?' + v,  controller: 'HongbaoListCtrl' })
      .when('/hongbao/detail', {  templateUrl: 'tpl/hongbao/detail.html?' + v,  controller: 'HongbaoDetailCtrl' })
      .when('/fa/sanfang/list', {templateUrl: 'tpl/fa/sanfang/list.html?' + v, controller: 'SanFangCtrl'})

      .when('/fa/downline/list', {templateUrl: 'tpl/fa/downline/list.html?' + v, controller: 'DownListCtrl'})
      .when('/fa/downline/view', {templateUrl: 'tpl/fa/downline/view.html?' + v, controller: 'DownViewCtrl'})
      //理财师内部

      .when('/fa/neibu/lcsmanlist', {templateUrl: 'tpl/fa/neibu/list.html?' + v, controller: 'LcsmanlistCtrl'})

      .when('/news/add', {templateUrl: 'tpl/news/add.html?' + v, controller: 'NewsAddCtrl'})
      .when('/news/list', {templateUrl: 'tpl/news/list.html?' + v, controller: 'NewsListCtrl'})

      .when('/roadVideo/add', {templateUrl: 'tpl/roadVideo/add.html?' + v, controller: 'roadVideoAddCtrl'})
      .when('/roadVideo/list', {templateUrl: 'tpl/roadVideo/list.html?' + v, controller: 'roadVideoListCtrl'})
      .when('/roadVideo/play', {templateUrl: 'tpl/roadVideo/play.html?' + v, controller: 'roadVideoPlayCtrl'})

      .when('/blindate/list', {templateUrl: 'tpl/blindate/list.html?' + v, controller: 'blindateListCtrl'})

      .when('/financier/list', {templateUrl: 'tpl/financier/list.html?' + v, controller: 'FinancierListCtrl'})
      .when('/financier/add', {templateUrl: 'tpl/financier/add.html?' + v, controller: 'FinancierAddCtrl'})

      .when('/shop/falist', {  templateUrl: 'tpl/shop/falist.html?' + v,  controller: 'ShopUserCtrl' })
      .when('/shop/faauit', {  templateUrl: 'tpl/shop/faauit.html?' + v,  controller: 'ShopFaViewCtrl' })
      //.when('/shop/view', {  templateUrl: 'tpl/shop/view.html?' + v,  controller: 'ShopFaViewCtrl' })
      .when('/shop/sucailist', {  templateUrl: 'tpl/shop/sucailist.html?' + v,  controller: 'ShopSucaiCtrl' })
      .when('/shop/sucaiadd', {  templateUrl: 'tpl/shop/sucaiadd.html?' + v,  controller: 'ShopSucaiAddCtrl' })

      .when('/updateOrder/add', {  templateUrl: 'tpl/updateOrder/add.html?' + v,  controller: 'UpdateOrderAddCtrl' })
      .when('/updateOrder/list', {  templateUrl: 'tpl/updateOrder/list.html?' + v,  controller: 'UpdateOrderListCtrl' })
      .when('/updateOrder/update', {  templateUrl: 'tpl/updateOrder/update.html?' + v,  controller: 'UpdateOrderCtrl' })
      .when('/product/updateDate', {  templateUrl: 'tpl/product/updateDate.html?' + v,  controller: 'UpdateProductDateCtrl' })

      .when('/shop/behavior/home', {  templateUrl: 'tpl/shop/behavior/home.html?' + v,  controller: 'BehaviorHomeCtrl' })
      .when('/shop/behavior/prod', {  templateUrl: 'tpl/shop/behavior/prod.html?' + v,  controller: 'BehaviorProdCtrl' })
      .when('/shop/behavior/cust', {  templateUrl: 'tpl/shop/behavior/cust.html?' + v,  controller: 'BehaviorCustCtrl' })
      .when('/shop/behavior/fp', {  templateUrl: 'tpl/shop/behavior/fp.html?' + v,  controller: 'BehaviorFpCtrl' })
      .when('/shop/behavior/footermenu', {  templateUrl: 'tpl/shop/behavior/footermenu.html?' + v,  controller: 'BehaviorFooterMenuCtrl' })
      .when('/shop/feedback/list', {  templateUrl: 'tpl/shop/feedback/list.html?' + v,  controller: 'ShopUserFeedBackList' })
      .when('/shop/background/list', {  templateUrl: 'tpl/shop/background/list.html?' + v,  controller: 'ShopBackGroundList' })
      .when('/shop/behavior/custregister', {  templateUrl: 'tpl/shop/behavior/custregister.html?' + v,  controller: 'BehaviorCustregisterList' })
      .when('/shop/behavior/cruxdata', {  templateUrl: 'tpl/shop/behavior/cruxdata.html?' + v,  controller: 'BehaviorCruxdataList' })

      .when('/shop/subject/list', {  templateUrl: 'tpl/shop/subject/list.html?' + v,  controller: 'ShopSubjectListCtrl' })


      // 数据统计
      .when('/statistics/register', { templateUrl: 'tpl/statistics/register.html?' + v, controller: 'statisticsRegisterCtrl'})
      .when('/statistics/registerRole', { templateUrl: 'tpl/statistics/registerRole.html?' + v, controller: 'statisticsRegisterRoleCtrl'})
      .when('/statistics/order', { templateUrl: 'tpl/statistics/order.html?' + v, controller: 'statisticsOrderCtrl'})
      .when('/statistics/orderUserPer', { templateUrl: 'tpl/statistics/orderUserPer.html?' + v, controller: 'statisticsOrderUserPerCtrl'})
      .when('/statistics/orderFauserRolePrpportion', { templateUrl: 'tpl/statistics/orderFauserRolePrpportion.html?' + v, controller: 'statisticsOrderFauserRolePrpportionCtrl'})
      .when('/statistics/orderFauserPrpportion', { templateUrl: 'tpl/statistics/orderFauserPrpportion.html?' + v, controller: 'statisticsOrderFauserPrpportionCtrl'})
      .when('/statistics/orderRanking', { templateUrl: 'tpl/statistics/orderRanking.html?' + v, controller: 'statisticsOrderRankingCtrl'})
      .when('/statistics/companyTotal', { templateUrl: 'tpl/statistics/companyTotal.html?' + v, controller: 'statisticsCompanyTotalCtrl'})

      .when('/shop/information/add', {  templateUrl: 'tpl/shop/information/addoredit.html?' + v,  controller: 'ShopInformationAddCtrl' })
      .when('/shop/information/edit', {  templateUrl: 'tpl/shop/information/addoredit.html?' + v,  controller: 'ShopInformationEditCtrl' })
      .when('/shop/information/list', {  templateUrl: 'tpl/shop/information/list.html?' + v,  controller: 'ShopInformationListCtrl' })
      .when('/shop/yxtactivity/list', {  templateUrl: 'tpl/shop/yxtactivity/list.html?' + v,  controller: 'jcsYxtActivityCount' })
      .when('/shop/yxtactivity/withdrawLogList', {  templateUrl: 'tpl/shop/yxtactivity/withdrawLogList.html?' + v,  controller: 'jcsYxtActivityDrawCount' })

      .when('/shop/total/edit', {  templateUrl: 'tpl/shop/total/edit.html?' + v,  controller: 'pcTotalDynamic' })
    .when('/shop/playopen/list', {  templateUrl: 'tpl/shop/playopen/list.html?' + v,  controller: 'playOpenApplyList' })

      //奖项配置
      .when('/salecon/salePrizes', {  templateUrl: 'tpl/salecon/salePrizeslist.html?' + v,  controller: 'salesPrizesListCtrl' })
      .when('/salecon/salePrizesPeople', {  templateUrl: 'tpl/salecon/salePrizesPeoplelist.html?' + v,  controller: 'salesPrizesPeopleListCtrl' })

        //一元早餐商家信息维护
      .when('/shop/yyzcact/list', {  templateUrl: 'tpl/shop/yyzcact/list.html?' + v,  controller: 'shopInfoListCtrl' })

        .when('/statistics/productKeyWord', { templateUrl: 'tpl/statistics/productKeyWord.html?' + v, controller: 'productKeyWordTotalCtrl'})

        .otherwise({  redirectTo: '/index' });
}]).config(['momentPickerProvider', function (momentPickerProvider) {
    momentPickerProvider.options({
        locale:"zh-cn",
    });
}]);

faApp.controller('ActivityAddCtrl',['$scope','activityService','$location','$controller','$route', '$filter', function($scope,activityService,$location,$controller,$route, $filter) {
  $scope.ctrlName = "ActivityAddCtrl";
  $scope.activityId = $location.search().activityId || '';
  
  $scope.activity = {
    activitiesName: '',
    activitiesDesc: '',
    activitiesSkipName: '',
    activitiesSkipLink: '',
    activitiesStartDateStr: '',
    activitiesEndDateStr: '',
    activitiesStatus: '01'
  };

  if($scope.activityId){
    activityService.activityById({id: $scope.activityId}).then(function(json){
      if (json.statusCode){
       alert(json.statusCode);
      }else{
        $scope.activity = json.projectActivities;

        $scope.activity.activitiesStartDateStr = $filter('date')(json.projectActivities.activitiesStartDate, "yyyy-MM-dd");
        $scope.activity.activitiesEndDateStr = $filter('date')(json.projectActivities.activitiesEndDate, "yyyy-MM-dd");
      }
    });
  }

  $scope.save = function(){
    if(!$scope.form.$invalid){
      var p = {};
      if ($scope.activityId){
        p = activityService.activityEdit;

        $scope.activity.activitiesStartDate = '';
        $scope.activity.activitiesEndDate = '';
      }else{
        p = activityService.activityAdd;
      }

      if((!$scope.activity.activitiesSkipName && $scope.activity.activitiesSkipLink) ||
         ($scope.activity.activitiesSkipName && !$scope.activity.activitiesSkipLink)){
        alert('活动产品专题跳转名称和活动专题跳转链接 必须都填写或不填写！');
        return;
      }

      p($scope.activity).then(function(json){
        if (json.statusCode){
          if(json.statusCode == '4015'){
            alert('活动Code已存在，请更换！');
          }else{
            alert(json.statusCode);
          }
        }else{
          alert('SUCCESS！');
          $location.path("/activity/list");
        }
      });
    }
  };

}]);

faApp.controller('ActivityListCtrl',['$scope','activityService','$location','$controller','$route',function($scope,activityService,$location,$controller,$route) {   
  $scope.ctrlName = "ActivityListCtrl";
  
  $scope.activityList = {};
  $scope.pager = {};

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.$watch('config',function(){
    activityService.activityList($scope.config).then(function(json){
      console.log(json);
      $scope.activityList = json.list;
      $scope.pager = json.pager;
    });
  },true);

}]);
faApp.controller('AdListCtrl',['$scope','adService','$location','$controller','$route',function($scope,adService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 
 
  $scope.ads = [];
  $scope.loading = true;

  $scope.$watch('config',function(){
    adService.adList($scope.config).then(function(json){
      $scope.ads = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.searchMap = {};
  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    $scope.config.pageNo = 1;
  };

  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.start = function(id){
    adService.adStart({id:id,status:"01"}).then(function(json){
      $route.reload();    
    });
  }; 

  $scope.stop = function(id){
    adService.adStop({id:id,status:"02"}).then(function(json){
      $route.reload();    
    });
  }; 
}]);

faApp.controller('AdAddCtrl',['$scope','adService','$location','$controller','$timeout',function($scope,adService,$location,$controller,$timeout) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.ad = {"advertSort":10};
  $scope.loading = true; 

  $scope.save = function(){
    if ($scope.form.$invalid){
      if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
      if ($scope.form.pic.$invalid)$scope.form.pic.$dirty = true;
      if ($scope.form.link.$invalid)$scope.form.link.$dirty = true;
      if ($scope.form.startTime.$invalid)$scope.form.startTime.$dirty = true;
      if ($scope.form.endTime.$invalid)$scope.form.endTime.$dirty = true;
      if ($scope.form.sort.$invalid)$scope.form.sort.$dirty = true;
    }else{
      if ($scope.ad.startTime){$scope.ad.startTime = $scope.ad.startTime + " 00:00:00";}
      if ($scope.ad.endTime){$scope.ad.endTime = $scope.ad.endTime + " 23:59:59";}

      $scope.ad.linkAddre = $scope.ad.linkAddre;
      $scope.ad.picAddre = $scope.ad.picAddre;
      adService.adAdd($scope.ad).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/list");
        }
      });
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      console.info(response)
      if (response.statusCode == "0000") {
        $scope.ad.picAddre = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });
}]);

faApp.controller('AdEditCtrl',['$scope','adService','$location','$controller','$routeParams','$filter',function($scope,adService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.ad = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;

  adService.adQuery($scope.id).then(function(json){
    $scope.ad = json.dto;
    if ($scope.ad.startTime){ $scope.ad.startTime = $filter("date")($scope.ad.startTime,"yyyy-MM-dd"); }
    if ($scope.ad.endTime){ $scope.ad.endTime = $filter("date")($scope.ad.endTime,"yyyy-MM-dd"); }

  });

  $scope.save = function(){
    if ($scope.form.$invalid){
      if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
      if ($scope.form.pic.$invalid)$scope.form.pic.$dirty = true;
      if ($scope.form.link.$invalid)$scope.form.link.$dirty = true;
      if ($scope.form.startTime.$invalid)$scope.form.startTime.$dirty = true;
      if ($scope.form.endTime.$invalid)$scope.form.endTime.$dirty = true;
      if ($scope.form.sort.$invalid)$scope.form.sort.$dirty = true;
    }else{
      if ($scope.ad.startTime){$scope.ad.startTime = $scope.ad.startTime + " 00:00:00";}
      if ($scope.ad.endTime){$scope.ad.endTime = $scope.ad.endTime + " 23:59:59";}

      $scope.ad.linkAddre = $scope.ad.linkAddre;
      $scope.ad.picAddre = $scope.ad.picAddre;
      adService.adEdit($scope.ad).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/list");
        }
      });
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.ad.picAddre = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });
}]);

faApp.controller('MsgListCtrl',['$scope','adService','$location','$controller','$routeParams','$filter','$route', function($scope,adService,$location,$controller,$routeParams,$filter,$route) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.msgs = [];
  $scope.loading = true;
  $scope.t=$routeParams.t;
  
  $scope.$watch('config',function(){
    adService.msgList($scope.config).then(function(json){
      $scope.msgs = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    //早报类型
    "type" : ($scope.t||"")
  };

  $scope.delete = function(id){
    adService.msgDelete(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("删除成功！");
        $route.reload();
      }
    });
  };
}]);

faApp.controller('MsgAddCtrl',['$scope','adService','$location','$controller','$routeParams','$filter', function($scope,adService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.msg = {};
  $scope.addOrUpdate = "添加资讯";

  $scope.t=$routeParams.t;
  if($scope.t){
     //初始化早报信息
    $scope.addOrUpdate="添加早报";
    //正文 初始化富文本
    $scope.msg.contents="<h3 style='margin: 10px 0;text-align: center'> 【资讯快览】 </h3> <p style='color: rgb(255, 0, 0); margin-top: 10px; text-align: left;'> 1、 百度、啊里、腾讯、京东、等耗资780亿入股 </p> <p style='text-align: left;'> 百度、啊里、腾讯、京东、等耗资780亿入股第三方离开过号开始 </p> <h3 style='text-align: center;'> <span style='text-align: center;'>&nbsp;【国际资讯】</span> </h3> <p style='color: rgb(255, 0, 0); margin-top: 10px; text-align: left;'> 1、 百度、啊里、腾讯、京东、等耗资780亿入股 </p> <p style='text-align: left;'> 百度、啊里、腾讯、京东、等耗资780亿入股第三方离开过号开始 </p>";
    $scope.msg.topContent="<p style='color: #ff0000;margin-top: 10px'> 1、百度、啊里、腾讯、京东、等耗资780亿入股 </p> <p> 百度、啊里、腾讯、京东、等耗资780亿入股第三方离开过号开始 </p> <p style='color: rgb(255, 0, 0); margin-top: 10px;'> <br/> </p>";
    //早报类型
    $scope.msg.type="10";
    $scope.msg.sort="2";
  }

  $scope.save = function(){
    if(!$scope.form.$invalid){
      adService.msgAdd($scope.msg).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/msg-list");
        }
      });
    }else{ 
      if(!$scope.msg.contents){
        alert("请填写正文！");
        return;
      }
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.msg.filePath = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });

}]);

faApp.controller('MsgUpdateCtrl',['$scope','adService','$location','$controller','$routeParams','$filter', function($scope,adService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.msg = {};
  $scope.id = $routeParams.id;
  $scope.addOrUpdate = "修改资讯";
  $scope.t=$routeParams.t;
  if($scope.t){
    $scope.addOrUpdate="修改早报";
  }
  if($scope.id){
    adService.msgDetail($scope.id).then(function(json){
      $scope.msg = json.dto;
    });
  }

  $scope.save = function(){
    if(!$scope.form.$invalid){
      adService.msgUpdate($scope.msg).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/msg-list");
        }
      });
    }else{
      if(!$scope.msg.contents){
        alert("请填写正文！");
        return;
      }
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.msg.filePath = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });

}]);

faApp.controller('ActListCtrl',['$scope','adService','$location','$controller','$routeParams','$filter', function($scope,adService,$location,$controller,$routeParams,$filter) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.acts = [];
  $scope.loading = true;
  $scope.$watch('config',function(){
    adService.actList($scope.config).then(function(json){
      $scope.acts = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "publicActivitiesId":0,
  };
         //点击事件显示消息
  $scope.changeShow=function(id){
    $scope.config.publicActivitiesId=id;
    adService.actPerList($scope.config).then(function(json){
     
      $scope.actPres = json.publicActivitiesPersonList;

      $scope.loading = false;
    });
      $scope.isShowOrder = true;
  }
}]);

faApp.controller('ActAddCtrl',['$scope','adService','$location','$controller','$routeParams','$filter', function($scope,adService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.act = {};
   // 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
$scope.dateFormat = function(dataValue)   
{ //author: meizz   


  var fmt = "yyyy-MM-dd hh:mm:ss";
  var o = {   
    "M+" : dataValue.getMonth()+1,                 //月份   
    "d+" : dataValue.getDate(),                    //日   
    "h+" : dataValue.getHours(),                   //小时   
    "m+" : dataValue.getMinutes(),                 //分   
    "s+" : dataValue.getSeconds(),                 //秒   
    "q+" : Math.floor((dataValue.getMonth()+3)/3), //季度   
    "S"  : dataValue.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (dataValue.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 

  $scope.save = function(){
    if(!$scope.form.$invalid){
      if($scope.act){
        if($scope.act.activitiesTotalPerson <= 0){
          alert("报名人数要大于0！");
          return;
        }
        if($scope.act.activitiesStartTime > $scope.act.activitiesEndTime){
          alert("结束时间要大于开始时间！");
          return;
        }
        if($scope.act.activitiesRegistEndTime > $scope.act.activitiesEndTime){
          alert("结束时间要大于报名结束时间！");
          return;
        }
      }

      
      $scope.act.activitiesStartTime = $filter("date")($scope.act.activitiesStartTime,"yyyy-MM-dd HH:mm:ss");
      $scope.act.activitiesEndTime = $filter("date")($scope.act.activitiesEndTime,"yyyy-MM-dd HH:mm:ss");
      $scope.act.activitiesRegistEndTime =  $filter("date")($scope.act.activitiesRegistEndTime,"yyyy-MM-dd HH:mm:ss");

      adService.actAdd($scope.act).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/act-list");
        }
      });
    }else{
      if(!$scope.act.activitiesRecomment){
        alert("请填写具体内容！");
        return;
      }
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        // $scope.act.activitiesImageUri = App.staticHost + response.attribute.fileUrl;
        $scope.act.activitiesImageUri = response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });

}]);

faApp.controller('ActUpdateCtrl',['$scope','adService','$location','$controller','$routeParams','$filter', function($scope,adService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.act = {};
  $scope.id = $routeParams.id;

  if($scope.id){
      adService.actDetail($scope.id).then(function(json){
      $scope.act = json.dto;
      $scope.act.activitiesImageUri = $scope.act.activitiesImageUri;
      $scope.act.activitiesStartTime = $filter("date")(json.dto.activitiesStartTime,"yyyy-MM-ddTHH:mm");
      $scope.act.activitiesEndTime = $filter("date")(json.dto.activitiesEndTime,"yyyy-MM-ddTHH:mm");
      $scope.act.activitiesRegistEndTime = $filter("date")(json.dto.activitiesRegistEndTime,"yyyy-MM-ddTHH:mm");
      delete $scope.act.activitiesPublishTime;
    });
  }

  $scope.save = function(){
    if(!$scope.form.$invalid){

      $scope.act.activitiesStartTime = $filter("date")($scope.act.activitiesStartTime,"yyyy-MM-dd HH:mm:ss");
      $scope.act.activitiesEndTime = $filter("date")($scope.act.activitiesEndTime,"yyyy-MM-dd HH:mm:ss");
      $scope.act.activitiesRegistEndTime =  $filter("date")($scope.act.activitiesRegistEndTime,"yyyy-MM-dd HH:mm:ss");
      adService.actUpdate($scope.act).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/ad/act-list");
        }
      });
    }else{
      if(!$scope.act.activitiesRecomment){
        alert("请填写具体内容！");
        return;
      }
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        // $scope.act.activitiesImageUri = App.staticHost + response.attribute.fileUrl;
        $scope.act.activitiesImageUri = response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });

}]);

faApp.controller('AdSuperList',['$scope','productService','$location','$controller','$route','adService','$routeParams',function($scope,productService,$location,$controller,$route,adService, $routeParams) {   
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.recommendList = [];

  $scope.$watch('config',function(){
    adService.adRecommendList($scope.config).then(function(json){
      $scope.recommendList = json.list;
      // $scope.pager = json.pager;
      // $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 100,
    "pageNo" : 1,
    "advertPosition" : '14'
  };

  $scope.toAddRecommend = function(){
    if($scope.recommendList && $scope.recommendList.length >= 5){
      alert("最多能有五项！");
      return;
    }else{
      $location.path("/super/add").search({t : $scope.config.advertPosition || '14'});
    }
  }

  $scope.start = function(id){
    adService.adStart({id:id,status:"01"}).then(function(json){
      $route.reload();    
    });
  }; 

  $scope.stop = function(id){
    var t = 0;
    angular.forEach($scope.recommendList,function(o){
      if(o.status == '01')
        t++;
    });
    if(t <= 2){
      alert("最少得有两项！");
      return;
    }
    adService.adStop({id:id,status:"02"}).then(function(json){
      $route.reload();    
    });
  };

}]);

faApp.controller('AdSuperAdd', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams', function($scope, productService, $location, $controller, $route, adService, $routeParams) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {
    title:'',
    pic:'',
    linkAddre:'',
    startTime:'1990-01-01 00:00:00',
    endTime:'3000-01-01 23:59:59',
    status:'01',
    advertSort:'1',
    picAddre:'',
    advertPosition: $routeParams.t || '10'
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adAdd($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/super/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);

faApp.controller('AdSuperEdit', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams','$filter' , function($scope, productService, $location, $controller, $route, adService, $routeParams, $filter) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {};
  $scope.id = $routeParams.id;

  if($scope.id){
    adService.adQuery($scope.id).then(function(json){
      $scope.recommend = json.dto;

      $scope.recommend.startTime = $filter("date")($scope.recommend.startTime,"yyyy-MM-dd") + " 00:00:00";;
      $scope.recommend.endTime = $filter("date")($scope.recommend.endTime,"yyyy-MM-dd") + " 23:59:59";
    });
  }

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adEdit($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/super/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });
}]);
faApp.controller('RoleListCtrl',['$scope','authService','$location','$controller','$route',function($scope,authService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    authService.roleList($scope.config).then(function(json){
      $scope.list = json.allGroup;
      $scope.pager = json.pager;
      $scope.loading = false;
    }); 
  },true)  
	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	};

	$scope.linkDelete = function(id){
    authService.linkDelete({id:id}).then(function(json){
      $route.reload();    
    });
	}; 
}]);

faApp.controller('RoleAddCtrl',['$scope','authService','$location','$controller','$timeout',function($scope,authService,$location,$controller,$timeout) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.allActions = {};
  $scope.selectActions = [];
  $scope.loading = true; 

  authService.urlList({}).then(function(json){
    $scope.actionList = json.actionList;
  });

	$scope.save = function(){
    if (!$scope.form.$invalid){ 
      var flag = false;
      for (var i in $scope.allActions){
        if ($scope.allActions[i]){
          flag = true;
          $scope.selectActions.push(i);
        }
      } 

      $scope.item['actionId'] = $scope.selectActions.join(",");
      authService.roleAdd($scope.item).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/role/list");
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
 
}]);

faApp.controller('RoleEditCtrl',['$scope','authService','$location','$controller','$routeParams','$filter',function($scope,authService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.allActions = {};
  $scope.selectActions = [];
  $scope.loading = true; 
  $scope.id = $routeParams.id; 

  authService.urlList({}).then(function(json){
    $scope.actionList = json.actionList;
  });

  authService.roleQuery($scope.id).then(function(json){
    $scope.item = json.groupInfo;
    angular.forEach(json.accessForGroup,function(o){
      $scope.allActions[o.actionId] = true;  
    });
  });

	$scope.save = function(){
    if (!$scope.form.$invalid){ 
      var flag = false;
      for (var i in $scope.allActions){
        if ($scope.allActions[i]){
          flag = true;
          $scope.selectActions.push(i);
        }
      } 

      $scope.item['actionId'] = $scope.selectActions.join(",");
      authService.roleEdit($scope.item).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/role/list");
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
 
}]);

faApp.controller('UrlListCtrl',['$scope','authService','$location','$controller','$route',function($scope,authService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    authService.urlList($scope.config).then(function(json){
      $scope.list = json.actionList;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	};

	$scope.linkDelete = function(id){
    authService.linkDelete({id:id}).then(function(json){
      $route.reload();    
    });
	}; 
}]);

faApp.controller('UrlAddCtrl',['$scope','authService','$location','$controller','$timeout',function($scope,authService,$location,$controller,$timeout) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true; 

	$scope.save = function(){
    if (!$scope.form.$invalid){ 

      authService.urlAdd($scope.item).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/url/list");
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
 
}]);
  




faApp.controller('BaseCtrl',['$scope','$timeout','$interval','$location','shareService','userService','loginService','adService','sessionService','ajaxService','faService',function($scope,$timeout,$interval,$location,shareService,userService,loginService,adService,sessionService,ajaxService,faService) {  

	$scope.sysVersion = faApp.sysVersion;
	$scope.env = App.env;
  

	$scope.beforeRender = function(){
		$scope.ngViewStyle = {display:"inherit"};
	};

	$scope.showNgView = function(){
		$scope.ngViewStyle = {display:"inherit"};
	}; 

	$scope.setLogined = function(user){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		$scope.loginStatus.loginName = user.userNickName;
		$scope.loginStatus.isLogin = true;
		$scope.loginStatus.uRole = user.uRole || "";
		$scope.loginStatus.name = user.userName;
		$scope.loginStatus.id = user.id;
		$scope.setCookieData("user",$scope.loginStatus,1);
	}; 

	$scope.logout = function(){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		$scope.loginStatus.isLogin = false;
		$scope.loginStatus.uRole = "";
		$scope.loginStatus.id = "";
		$scope.setCookieData("user",$scope.loginStatus,1);
	};

	$scope.isLogin = function(){
		var cu = $scope.getCookieData("user","{}",1);
		return cu.isLogin;
	}; 

	$scope.updateCookie = function(user){
		$scope.loginStatus = $scope.getCookieData("user","{}",1);
		user.uRole && ($scope.loginStatus.uRole = user.uRole);
		(user.name != undefined) && ($scope.loginStatus.name = user.name);
		$scope.setCookieData("user",$scope.loginStatus,1);
	};

	$scope.setCookieData = function(k,v,mapFlag){
		$scope.setLocalCookie(k,mapFlag ? angular.toJson(v) : v);
	};

	$scope.getCookieData = function(k,v,mapFlag){
		var v = $scope.getLocalCookie(k,v);
		return mapFlag ? angular.fromJson(v) : v;
	}

	$scope.removeCookieData = function(k){
		$scope.removeLocalCookie(k);
	} 

	$scope.setLocalCookie = function(k,v,cfg){
		Cookies.set(k, v, cfg);
	};

	$scope.getLocalCookie = function(k,d){
		var v = Cookies.get(k);
		return v ? v : d;
	}

	$scope.remembermeHandler = function(model){
		if ($scope.rememberme){
			$scope.setLocalCookie('login.name', model.loginName, { expires: 86400 * 365}); // Expires in 1 years
		}else{
			$scope.setLocalCookie('login.name', "", { expires: 86400 * 365}); // Expires in 1 years
		}
	};

	$scope.checkLogin = function(){
		if (!this.isLogin()){
			this.setCookieData("lastUrl",$location.path());
			$location.path("/login");
		}
	};

	$scope.getShowName = function(){
		return this.loginStatus.name ? this.loginStatus.name : (this.loginStatus.loginName || "");
	};

	$scope.alerts = [];
	$scope.addAlert = function(text,timeout) {
		$scope.alerts.push({type : 'success',msg: text});
		$timeout(function(){
			$scope.closeAlert(0);
		},timeout || 3000000);
	};

	$scope.alertNextPage = function(text,timeout){
		shareService.set("nextAlert",text);
	}; 

	$scope.alertFromShareService = function(){
		var text = shareService.get("nextAlert");
		if (text){
			shareService.remove("nextAlert");
			var a = shareService.get("nextAlert");
			this.addAlert(text);
		}
	};

	$scope.closeAlert = function(index) {
		$scope.alerts.splice(index, 1);
	};

	$scope.toggleShow = function(el){
		var a = 1;
	};

	$scope.isCorp = function(){
		return this.loginStatus.uType == "1";
	};

	$scope.isCorpFA = function(){
		return this.loginStatus.uType == "3";
	};

	$scope.isFreeFA = function(){
		return this.loginStatus.uType == "0";
	};

	$scope.isNotAuth = function(){
		//return this.loginStatus.uRole == "1";
		return false;//20141023,不认证也可以预约
	};

	$scope.isStatusBuyable= function(product){
		return product.saleStatus != "04" && product.saleStatus !="05";
	};

	$scope.makeActualRoute = function($route){
		var rawPath = $route.originalPath || "", 
			params = $route.params || {}
			path = "",
			varName = "",
			varFlag = false,
			length = rawPath.length;

			for (var i = 0;i < length;i ++){
				var c = rawPath[i];
				if (c == ':'){
					varFlag = true;
				}else if(varFlag && c == '/'){
					path += (params[varName] || "");
					varFlag = false;
					varName = "";
				}else if(varFlag){
					varName += c;
				}else{
					path += c;
				}
			}

		if(varName) path += (params[varName] || "");
		return path;
	};


	$scope.clearFieldValidation = function(field){
		field = field || {}; 
		try{
			field.$error = {};
		}catch(e){} 
	};

	$scope.markFieldError = function(field,k){
		if (!field)return;
		$scope.clearFieldValidation(field);
		field.$valid = false;	
		field.$invalid = true;
		field.$dirty = true;	
		field.$error[k] = true;	
		return field;
	};

  $scope.historyBack = function(){
    window.history.back(-1);
  };

  $scope.onUploadFile = function(cfg){
    cfg.onReady && cfg.onReady();
    
    $timeout(function(){
      $(".add-pic-btn").each(function(){
        $.jUploader({
          button: $(this),
          action: App.apiHost + '/fileUpload.shtml?callback=angular.callback._1000&fileType=' + (cfg.type || 'advertImage')+'&refid=' + (cfg.refid || ''),
          onUpload: function (fileName) {
            cfg.onUpload && cfg.onUpload(fileName);
          },
          onComplete: function (fileName, response,id) {
            cfg.onComplete && cfg.onComplete(fileName,response,id);
          },
          onCancel: function (fileName) {
            cfg.onCancel && cfg.onCancel(fileName);
          },
          showMessage: function (message) {
            cfg.showMessage && cfg.showMessage(message);
          }
        });
      });
    },2000); 
  };

  $scope.checkLoginStatus = function(){
    loginService.loginStatus().then(function(json){
      if (!json.loginStatus){
        $location.path("/login");
      }    
    });
  };

  $scope.setNavModule = function(v){
    $scope.nav.module = v;
  };
// 新增product.status == 4  金融产品内部审核中   写死的方旭id审核
  $scope.isPassVerifyable4 = function(product){
    product = product || {};
    var s = (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 4);
    return s&&($scope.loginStatus.loginName=='方旭'||$scope.loginStatus.loginName=='admin');
  };

  $scope.isPassVerifyable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 1||product.status == 6);
  };

// 新增product.status == 5 发布审核中    写死的李总id审核
 $scope.isPassPublishable5 = function(product){
    product = product || {};
    var s = (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 5);
    return s&&($scope.loginStatus.loginName=='李宏彪'||$scope.loginStatus.loginName=='admin');
  };

  $scope.isPassPublishable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1 || product.pPublicStatus == 4) && (product.status == 2);
  };

  $scope.isStopable = function(product){
    product = product || {};
    return (product.pPublicStatus == 2);
  };

  $scope.isPassEstablishable = function(product){
    product = product || {};
    return (product.pPublicStatus == 2 && !product.pEstablishmentTime);
  };

  $scope.isDeleteable = function(product){
    product = product || {};
    return (product.pPublicStatus == 1);
  };

  $scope.hasAuth = function(where,who){
    var _access = sessionService.getItem("user.access",""),authFlag = false;
    if (_access == "all"){
      return true;
    }
    angular.forEach(who.split(","),function(o){
      var realUrl = ajaxService.getApiUri(o);
          urlPaths = realUrl.split("/"),
          lastUrlPath = urlPaths[urlPaths.length - 1];
          if (_access.indexOf(lastUrlPath) != -1){
            authFlag = true 
          }
    });
    return authFlag;
  };

  $scope.checkBrowserEnv = function(){
    $scope.envIsOk = true;
    $scope.envMap = {};
    if (!window.sessionStorage){
      $scope.envIsOk = false;
    }
    if (window.attachEvent){
      $scope.envMap['isIE'] = true;
    }
  };
  
  
  $scope.watchIsChange = function(){
    $scope.lastConfig = $scope.lastConfig || {};
    $scope.config = $scope.config || {};
    delete $scope.lastConfig.callback;
    delete $scope.config.callback;
    var last = angular.toJson($scope.lastConfig);
    var now = angular.toJson($scope.config);
    //// console.log(last);
    //// console.log(now);
    if (last != now){
      $scope.lastConfig = App.cloneJson($scope.config);
      return true;
    }else{
      return false;
    };
  };

   //huqy   机构筛选
  $scope.sfCompanyList = {};
  $scope.isShowSelectCompany = false;
  $scope.isNewCompany = false;
  $scope.newCompanyName = '';
  $scope.showJigouCompany = function(name){
    console.log(name);
    $scope.isNewCompany = false;
    if(name){
      // 根据name查询列表
      //if(name.length >= 2){
        //$scope.isShowSelectCompany = true;
        faService.jigouQuery({'investOwnerName': name}).then(function(json){
          $scope.sfCompanyList = json.list;
          if(json && $scope.sfCompanyList.length <= 0){
            $scope.isNewCompany = true;
            $scope.newCompanyName = name;
            $scope.isShowSelectCompany = false;
          }else{
            $scope.isShowSelectCompany = true;
          }
        });
      //}
    }else{
      $scope.isShowSelectCompany = false;
    }

  }

  $scope.keyupChange=function(e,v){
    console.log(e);
    //空格键、回车键、1-9键盘  直接进行调用
    if(e.keyCode==32 || e.keyCode==13 || (e.keyCode>=49 && e.key<=53)){
      if(v=='ac'){
        //供应方
        $scope.queryAccessCompany=$('#queryAccessCompany').val();
      }else if(v=='ucn'){
        //三方机构   白名单公司
        $scope.uCompanyName=$('#uCompanyName').val();
        $scope.showSanfangCompany($scope.uCompanyName);
      }else{
        //机构
       $scope.product.pInvestOwner=$('#pInvestOwner').val();
       $scope.showJigouCompany($scope.product.pInvestOwner);
      }
    }
  }
  $scope.selectedJigouCompany = function(name){
    $scope.isShowSelectCompany = false;
    $scope.product.pInvestOwner = name;
  }
  
  ///////机构

//全局打开table页面
  $scope.changeClickNone = function(datauri,dataid,name){
    var x=top.document.getElementById('noneclick');
    $(x).attr('data-id',dataid);
    $(x).attr('data-uri',datauri);
     $(x).text(name);
    top.document.getElementById('noneclick').click();
  }

	$scope.sexMapModel = [ { value:1,text:"男"}, { value:2,text:"女"}, { value:3,text:"保密"}, ]; 
	$scope.payStatusMapModel = [ { value:1,text:"预约"}, { value:2,text:"签约"}, { value:3,text:"返佣"}, ];
	$scope.productLevelMapModel = [ { value:'01',text:"AAA"}, { value:'02',text:"AA"}, { value:'03',text:"A"}, { value:'04',text:"BBB"}, { value:'05',text:"BB"}, { value:'06',text:"B"}, { value:'07',text:"CCC"}, { value:'08',text:"CC"}, { value:'09',text:"C"}, { value:'10',text:"D"} ];
	$scope.newsTypeMapModel = App.newsTypeMapModel;
	$scope.publicAreaModel = App.publicAreaModel;
	$scope.paymentInterestTypeModel = App.paymentInterestTypeModel;
	$scope.investTypeModel = App.investTypeModel;
	$scope.pLevelModel = App.pLevelModel;
	$scope.advertPositionModel = App.advertPositionModel;
	$scope.productStatusModel = App.productStatusModel;
	$scope.productPublicStatusModel = App.productPublicStatusModel;
	$scope.productTypeModel = App.productTypeModel;
  $scope.dictMap = App.dictMap;

	$scope.globalSetting = App.globalSetting;
	$scope.loginStatus = $scope.getCookieData("user","{}",1); 

	$scope.apiHost = App.apiHost;
	$scope.staticHost = App.staticHost;

	$scope.alertFromShareService();

}]);
faApp.controller('BaseListCtrl',['$scope','$controller','sessionService','$timeout',function($scope,$controller,sessionService,$timeout) {  
  
	$controller('BaseCtrl', {$scope: $scope}); 

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
	};

  $scope.searchMap = {};
  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    $scope.config.pageNo = 1;
    console.log($scope.config);

    !notsave && $scope.saveLastSearchConfig();
  };
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
    $timeout(function() {
      $(window).scrollTop(0);
    }, 200);
	}; 
  
  $scope.getLastSearchConfig = function(){
    var cfgStr = sessionService.getItem($scope.getLastSearchConfigKey(),"{}");
    $scope.searchMap = angular.fromJson(cfgStr);
    /*$scope.clearLastSearchConfig();*/
  };
  
  $scope.saveLastSearchConfig = function(){
    sessionService.setItem($scope.getLastSearchConfigKey(),angular.toJson($scope.searchMap));
  };
  
  $scope.clearLastSearchConfig = function(){
    sessionService.removeItem($scope.getLastSearchConfigKey());
  };
  
  $scope.getLastSearchConfigKey = function(){
    return "cfg_" + $scope.getCtrlName();
  };
  
  $scope.getCtrlName = function(){
    $scope.ctrlName = $scope.ctrlName || ((new Date()).getTime() + "");
    return $scope.ctrlName;
  };
  
  $scope.getLastSearchConfig();
  $scope.search(1);
 
}]);


faApp.controller('BehaviorCtrl', ['$cookieStore','$scope','$routeParams','beService','$location', '$controller', function($cookieStore,$scope,$routeParams,beService, $location, $controller) {
	$controller('BaseListCtrl', {
		$scope: $scope
	});
	$scope.userList = [];
	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	}
	//设置默认的查询参数
	if($routeParams.startDate){
		$scope.searchMap['startDate'] = $routeParams.startDate;
	}
	if($routeParams.endDate){
		$scope.searchMap['endDate'] = $routeParams.endDate;
	}
	if($routeParams.flagLogin){
		$scope.searchMap['flagLogin'] = $routeParams.flagLogin;
	}
	if($routeParams.ip){
		$scope.searchMap['ip'] = $routeParams.ip;
	}
	// if($routeParams.loginName){
	// 	$scope.searchMap['loginName'] = $routeParams.loginName;
	// }
	if($routeParams.isSearch){
		$scope.search()
	}
	
	console.log($scope.config);
	$scope.$watch('config', function(cfg) {
		if ($scope.watchIsChange()) {
			beService.getDataList($scope.config).then(function(json){

		        $scope.userList = json.list || [];
		        $scope.pager = json.pager;
		        $scope.searchMap['startDate'] = $scope.searchMap['startDate'] ? $scope.searchMap['startDate'] : json.nowDate;
		        $scope.searchMap['endDate'] = $scope.searchMap['endDate'] ? $scope.searchMap['endDate'] : json.nowDate;

			})
		}
	}, true);

	// $scope.searchMap.flagLogin = 2; //默认未登录
	$scope.search = function() {
		angular.forEach($scope.searchMap, function(o, i) {
			$scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
		});

	};
	var query = [];
	$scope.toView = function(cfg) {
		var name = $scope.config.loginName;
		$scope.config.loginName = name ? name : cfg;
		angular.forEach($scope.config,function(o,i){
			query.push(i + "=" + $scope.config[i]);
		}) 
		var url = 'behavior/view?'+query.join("&");
		// alert(url);
		$location.url(url);
	}

}]);
faApp.controller('BehaviorViewCtrl',['$scope','beService','$routeParams','$location','$controller',function($scope,beService,$routeParams, $location, $controller) {
	$controller('BaseListCtrl', {
		$scope: $scope
	});	
	console.log('BehaviorViewCtrl');
	$scope.arr = $routeParams;
	$scope.staticHost=App.staticHost;
	var query = [];
	angular.forEach($scope.arr,function(o,i){
		query.push(i + "=" + $scope.arr[i])
	})
	$scope.url = '#/behavior/list?isSearch=1&'+query.join("&");
	$scope.behavior = {
		remarkInfo : ''
	};
	
	beService.getDateInfo($scope.arr).then(function(json){
		
		$scope.btnList = json.info;
		// var result = btnTypeNoRepeat(json.info);//去掉重复点击的type
	}) 
	
	$scope.addRemark = function() {
		if( $scope.behavior.remarkInfo.length > 250 ) {
			alert("输入文字过长，请数日250个字之内");
			return
		}else if( $scope.behavior.remarkInfo.length == 0 ){
			alert("输入文字内容");
			return
		}
		beService.addRemark({loginName : $scope.arr.loginName, remark : $scope.behavior.remarkInfo}).then(function(json){
		  if (!json.statusCode){
			beService.faUserVisit($scope.arr.loginName).then(function(json){
			  $scope.visitList = json.list;
			});
			$scope.behavior.remarkInfo = "";
		  }else{
			alert("出错了:" + json.statusCode);
		  }  
		});
	} 
	
	$scope.visitList = [];
	beService.faUserVisit($scope.arr.loginName).then(function(json){
		$scope.visitList = json.list;
	});
	
}]);
// //去除重复的点击
// function btnTypeNoRepeat(arr) {

// 	var result = [],
// 		isRepeated;
// 	for (var i = 0 ; i < arr.length; i++) {
// 		isRepeated = false;
// 		for (var j = 0 ; j < result.length; j++) {
// 			if (arr[i].type == result[j].type) {
// 				isRepeated = true;
// 				break;
// 			}
// 		}
// 		if (!isRepeated) {
// 			result.push(arr[i]);
// 		}
// 	}
// 	return result;
// }

faApp.controller('BidProductListCtrl',['$scope','bidProductService','$location','$controller','$route','$routeParams','sessionService',function($scope,bidProductService,$location,$controller,$route,$routeParams,sessionService) {

 $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.showEstablishaFormFlag=false;
  $scope.showPublishFailFormFlag=false;
  $scope.config={
    "pType":"",
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.config['orderBy'] = $routeParams.orderBy || '',
  $scope.config['orderByTag'] = $routeParams.orderByTag || '',
  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  //排序
  $scope.orderbyFreqMap = {
    "createDate":["desc","asc"]
  };


  $scope.param={
    "pType":"",
    "id":"",
    "biddingStatus":"2",
    "failReson":"",
  };
  $scope.showResonFlag=false;
  $scope.searchMap = {};
  $scope.config.pType = $routeParams.t;
  $scope.searchMap.pType = $routeParams.t;
  $scope.param.pType = $routeParams.t;

  $scope.$watch('config',function(){

    bidProductService.bidProductList($scope.config).then(function(json){
      $scope.list = json.fpBiddingReceiptList;
      $scope.pager=json.pager;
    });
  },true);

  $scope.showFailResonInput=true;
  $scope.passUpdate =function(v){
  
    if(v=='2'){
      $scope.showFailResonInput=true;
    }else{
      $scope.showFailResonInput=false;
    }
  }

  $scope.orderby = function(field){
   
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
  
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  }
  $scope.showHide = function(id,who) {
    $scope.param.id = id;
    if(who == 1) {
      $scope.showEstablishaFormFlag = true;
    }else{
      $scope.showPublishFailFormFlag = true;     
    }
  }

  $scope.changeStatus = function(status) {
    var addAnwer = false;
    if(status == '2' || status=='6'){
      addAnwer = true;
    }
    if (addAnwer && !$scope.param.failReson) {
      alert("请填写原因");
      return;
    } else {
      $scope.param.biddingStatus = status;
      bidProductService.bidProductStatus($scope.param).then(function(json) {
        if(json.statusCode == '4010') {
          alert('没有缴保证金');
        }else if(json.statusCode == '4011'){
          alert('产品收益区间无');
        }else{
          alert('更改成功');
          addAnwer = false;
          $route.reload();
        }
      })
    }
  }
  $scope.search = function(){
    console.log($scope.searchMap);
    angular.forEach($scope.searchMap, function(o, i) {
      // console.log(i);
      $scope.config[i] = $scope.searchMap[i] || "";
      console.log($scope.config);
    });
  };
  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }
}]);

faApp.controller('BidProductDetailCtrl',['$scope','bidProductService','$location','$controller','$route','$routeParams',function($scope,bidProductService,$location,$controller,$route,$routeParams) {
    $scope.id = $routeParams.id;
    $scope.t = $routeParams.t;//设置产品类型
    bidProductService.bidProductDetail($scope.id).then(function(json){
      $scope.detail = json.fpBiddingReceiptDetail;
    });
}]);
faApp.controller('blindateListCtrl', ['$cookieStore','$scope','$routeParams','blindateService','$location', '$controller','$route', function($cookieStore,$scope,$routeParams,blindateService, $location, $controller,$route) {
	$controller('BaseListCtrl', {
		$scope: $scope
	});

	$scope.config = {
		pageNo:1,
		PageSize:20
	};
	$scope.editQunName = false;
	$scope.editData = {};
	$scope._id = ''; //传入的id

	$scope.$watch('config', function() {
		blindateService.getDataList($scope.config).then(function(json){
			if(json.statusCode){
				alert('出错了'+json.statusCode)
			}else{
				$scope.list = json.list;
				$scope.pager = json.pager;
			};
		})
	}, true);

	$scope.showHask = function(id,v){
		$scope.editQunName = true;
		$scope._id = id;
		$scope.editData.wechatGroup = v;
	};

	$scope.edit = function(type,id){
		$scope.editData.id = id;	

		if ($scope.editData.wechatGroup) {
			$scope.editData.isJoinWechat = 1; //已加入
		} else {
			$scope.editData.isJoinWechat = 0; //未加入
		};

		blindateService.dateUpdata($scope.editData).then(function(json) {
			if (json.statusCode) {
				alert('出错了');
			} else {
				$scope.editQunName = false;
				blindateService.getDataList($scope.config).then(function(json){
					if(json.statusCode){
						alert('出错了'+json.statusCode)
					}else{
						$scope.list = json.list;
						$scope.pager = json.pager;
					};
				})
			}
		});
	};


	$scope.orderby = function(v) {
		if (v == 'createDate') {
			$scope.config.orderParameter = '01';
		} else if (v == 'updateDate') {
			$scope.config.orderParameter = '02';
		} else if (v == 'playNum') {
			$scope.config.orderParameter = '03';
		};
		if ($scope.config.orderType == '01') {
			$scope.config.orderType = '02';
		} else {
			$scope.config.orderType = '01';
		}

	};

}]);


faApp.controller('CompanyListCtrl',['$scope','companyService','$location','$controller','$route',function($scope,companyService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.companys = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    companyService.companyList($scope.config).then(function(json){
      $scope.companys = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
		"cName" : '',
	};

  $scope.searchMap = {
		"cName" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 

  $scope.deleteCompany = function(id){
    companyService.companyDelete(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("删除成功");
        $route.reload();
      }
    });
  };
}]);

faApp.controller('CompanyAddCtrl',['$scope','companyService','$location','$controller','$timeout',function($scope,companyService,$location,$controller,$timeout) {   
	$controller('BaseListCtrl', {$scope: $scope}); 

  $scope.company = {};
  $scope.loading = true; 

	$scope.save = function(){
    if ($scope.form.$invalid){
      return;
    }else{
      companyService.companyAdd($scope.company).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/company/list");
        }
      });
    }
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.company.cShortImageUri = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  }); 
}]);

faApp.controller('CompanyEditCtrl',['$scope','companyService','$location','$controller','$routeParams','$filter',function($scope,companyService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.company = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;

  companyService.companyQuery($scope.id).then(function(json){
    $scope.company =  json.dto;
  });

	$scope.save = function(){
    if ($scope.form.$invalid){
      return;
    }else{
      companyService.companyEdit($scope.company).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/company/list");
        }
      });
    }
  };


  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.company.cShortImageUri = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  }); 
}]);


faApp.controller('CompanyViewCtrl',['$scope','companyService','$location','$controller','$routeParams','$filter',function($scope,companyService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;

  companyService.companyQuery($scope.id).then(function(json){
    $scope.company = json.dto;
  });

}]);
 
faApp.controller('CompanySubCtrl',['$scope','companyService','$location','$controller','$route',function($scope,companyService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.companys = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    companyService.subList($scope.config).then(function(json){
      $scope.companys = json.list;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
		"subType" : '01',
	};

  $scope.searchMap = {
		"subType" : '', 
		"subMail" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 

  $scope.deleteCompany = function(id){
    companyService.companyDelete(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("删除成功");
        $route.reload();
      }
    });
  };
}]);


faApp.controller('FaListCtrl',['$scope','faService','$location','$rootScope','$controller','$route','$routeParams','exportService','licaishiManagerService','sessionService','$cookieStore','$cookies',function($scope,faService,$location,$rootScope,$controller,$route,$routeParams,exportService,licaishiManagerService,sessionService,$cookieStore,$cookies) {
  $scope.ctrlName = "FaListCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.fas = [];
  $scope.black = {blackType:1};
  $scope.vtype="";
  if($routeParams.orderFlag=="1"&&$routeParams.notHasVisit){
    $scope.vtype="成交客户列表";
  }else if($routeParams.orderFlag=="2"&&$routeParams.notHasVisit){
    $scope.vtype="待沉寂理财师列表";
  }else if($routeParams.notHasVisit){
    $scope.vtype="待回访理财师列表";
  }else if($routeParams.notHasCheck){
    $scope.vtype="待审核理财师列表";
  }else if($routeParams.isnoManagerUserLicaishi){
    $scope.vtype="待分配理财师列表";
  }else{
    $scope.vtype="所有理财师列表";
  }

  if($routeParams.newPage){
    console.info($routeParams.isEmptyParam)
    if($routeParams.isEmptyParam){
        $scope.searchMap={isnoManagerUserLicaishi:"",notHasVisit:""
        ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",systemUserId2:"",
          "pageSize" : 20,   "pageNo" : 1
       };
       $scope.config={isnoManagerUserLicaishi:"",notHasVisit:""
        ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",
            "pageSize" : 20,   "pageNo" : 1
       };
    }
    $scope.listWhere="";
    if($routeParams.isnoManagerUserLicaishi){//待分配
      $scope.searchMap.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
      $scope.config.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
      $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
    }
    if($routeParams.notHasVisit){//是否回访
      $scope.searchMap.notHasVisit=$routeParams.notHasVisit;
      $scope.config.notHasVisit=$routeParams.notHasVisit;
      $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
    }
    if($routeParams.notHasCheck){//待审核
      $scope.searchMap.notHasCheck=$routeParams.notHasCheck;
      $scope.config.notHasCheck=$routeParams.notHasCheck;
       $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
    }
    if($routeParams.orderFlag){//是否交易    1 成交客户
      $scope.searchMap.orderFlag=$routeParams.orderFlag;
      $scope.config.orderFlag=$routeParams.orderFlag;
      $scope.config.showOrderFlag=true;
      $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
    }
    console.info($routeParams.systemUserId)
    if($routeParams.systemUserId){//当前用户ID  我的客户列表
      $scope.searchMap.systemUserId=$routeParams.systemUserId;
      $scope.config.systemUserId=$routeParams.systemUserId;
      //$scope.searchMap.systemUserId2=$routeParams.systemUserId;
      $scope.config.showSystemUser=true;
      $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
    }
    if($routeParams.pageNo){//当前用户ID  我的客户列表
      $scope.searchMap.pageNo=$routeParams.pageNo;
      $scope.config.pageNo=$routeParams.pageNo-0;
    }

    if(($routeParams.orderFlag==2&&$routeParams.notHasVisit)||$routeParams.orderFlag==1){
      $scope.showVisit=true;
      if($routeParams.orderFlag==2&&$routeParams.notHasVisit){
         $scope.showVisitWhere=true;
      }else{
        $scope.showVisitWhere=false;
      }
    }
  }

  $scope.config1={"pageSize" : 10000};
  var sss={"userId":"*","username":"*无服务顾问*"};
  if(!$scope.config.showSystemUser){

    licaishiManagerService.list($scope.config1).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList = json.list;
          $scope.licaishiManagerUserList.push(sss);
          $scope.loading = false;
        }
      });


  }else{
    licaishiManagerService.otherList($scope.config1).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.licaishiManagerUserList = json.list;
        $scope.licaishiManagerUserList.push(sss);
        $scope.loading = false;
      }
    });
  }



  $scope.chkAllLicaishiList = function(){
    if($("#chkAllLicaishiList").attr("checked") == "checked"){
      $("[name='chkLicaishiList']").attr("checked","checked");
    }else{
      $("[name='chkLicaishiList']").attr("checked",false);
    }
  }

  $scope.licaishiManage = function(t){
    chooseLicaishiList(t);
    if($scope.chooseLicaishiId != undefined && $scope.chooseLicaishiId != ""){
      $scope.chooseLicaishiIdCount = $scope.chooseLicaishiId.split(",").length - 1;
      $scope.isShowLicaishiManagerLayer = true;
    }else{
      alert("请选择理财师！");
      return;
    }
    if(t != undefined && t != "" && t == "1"){
      licaishiManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };
  chooseLicaishiList = function(t){
    $scope.chooseLicaishiId = "";
    $scope.omu = "";
    $("[name='chkLicaishiList']").each(function(i){
      if($(this).attr("checked") == "checked"){
        //if(t == 1 && $(this).attr("omu")){
        //  alert("请选择未分配的理财师！");
        //  $scope.chooseLicaishiId = -1;
        //  return false;
        //}else
        if(t == 0 && !$(this).attr("omu")){
          alert("请选择已分配的理财师！");
          $scope.chooseLicaishiId = -2;
          return false;
        }
        if($(this).attr("value") != undefined && $(this).attr("value") != ""){
          $scope.chooseLicaishiId += $(this).attr("value") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
  };
  $scope.managerLicaishi = {};
  $scope.loading=false;
  $scope.fenpeiOrHuishou = function(t){
    
    if($scope.chooseLicaishiId!=null&&$scope.chooseLicaishiId!=undefined){
      $scope.managerLicaishi.licaishiIds=$scope.chooseLicaishiId.substring(0, $scope.chooseLicaishiId.length - 1);
    }
    if(t == "1"){
      if($scope.managerLicaishi.systemUserId != undefined && $scope.managerLicaishi.systemUserId != "" && t != ""){
       //关闭分配按钮
        $scope.loading=true;
        $scope.isShowLicaishiManagerLayer=false;
        // 分配操作
        licaishiManagerService.managerLicaishiUserAdd($scope.managerLicaishi).then(function(json){
         //放开分配按钮
           $scope.loading=false;
          if (json.statusCode){
               alert("出错了:" + json.statusCode);
          }else{
            // 操作成功！分配成功！
            var _map = json.map;
            if(_map.not_aCount>0){
              alert('A类分配超出上限，失败'+_map.not_aCount);
            }else if(_map.not_okCount>0){
              alert('OK类分配超出上限，失败'+_map.not_okCount);
            }else {
              $scope.alertNextPage("分配成功！");
            }
            $route.reload();
          }
        },function(res){
          alert('网络状态不稳定或超时！');
        });
      }else{
        alert("请选择服务顾问！");
      }
    }else if(t == '0'){
      var tmpid = "";
      angular.forEach($scope.omu.split(","),function(o,i){
        if(i == 0){
          tmpid = o;
        }else{
          if(o != undefined && o != "" && o != tmpid){
            tmpid = "-99";
          }
        }
      });
      if(tmpid != undefined && tmpid != "-99"){
        //关闭分配按钮
        $scope.loading=true;
        $scope.isShowLicaishiManagerLayer=false;
        // 回收时，理财师服务顾问设为空
        $scope.managerLicaishi.systemUserId = "";
        // 回收
        licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function(json){
         //放开分配按钮
            $scope.loading=false;
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      }else{
        if(confirm("选择了多个理财师，且服务顾问人不同，确认要同时回收吗！")){
          //关闭分配按钮
            $scope.loading=true;
          $scope.isShowLicaishiManagerLayer=false;
          // 回收时，服务理财师设为空
          $scope.managerLicaishi.systemUserId = "";
          // 回收
          licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function(json){
             //放开分配按钮
            $scope.loading=false;
            if(json.statusCode== "4002"){
              alert("存在已分配理财师，请先收回，后分配！");
            }else if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }

  }
  $scope.config['orderBy'] = $routeParams.orderBy || '',
  $scope.config['orderByTag'] = $routeParams.orderByTag || '',

  $rootScope.viewNextBtn = {
    listWhere : $scope.listWhere

  }
  console.log($scope.config)
  $scope.$watch('config',function(){
    console.log('config-up');
    if ($scope.watchIsChange()){
      $scope.loading=true;
      faService.faList($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
        $rootScope.myKeHuNowPageListSize = json.list || [];
        $rootScope.viewNextBtn.pageNo = $scope.pager.pageNo;
        var arr = [];
        for(t in json.list){
          arr.push(json.list[t].id);
        }
        $scope.loading=false;
        $cookies.myKeHuNowPageListSize = angular.toJson(arr);
      });
    }
  },true);
  //读取查询 seeionStronge
  $scope.getLastSearchConfig();
  // $scope.search();

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {
    "createDate":["desc","asc"],
    "lastLoginTime":["desc","asc"],
    "latestVisitTime":["desc","asc"],
    "addAuthDate":["desc","asc"]
  };
  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  }

  $scope.toViewPage = function(id){
    var url = 'fa/view?id=' + id + $scope.listWhere + '&pageNo=' + $scope.config.pageNo;
    $location.url(url);
  }

  $scope.showBlackAddForm = function(id){
    $scope.black.userId = id;
    $scope.showBlackAddFormFlag = true;
  };

  $scope.blackAdd = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };

  $scope.cert = {id:""};
  $scope.showCertForm = function(id){
    $scope.cert.id = id;
    $scope.showCertFormFlag = true;
    
  };
  $scope.certSave = function(){
    if (!$scope.certform.$invalid){
      if ($scope.cert.type && $scope.cert.uRole != "99"){
        $scope.cert.uRole = $scope.cert.type;
      }
      if (!$scope.cert.uRole || ($scope.cert.uRole == "2" && (!$scope.cert.type))){
        alert("请选择评级");
        return;
      }
      faService.certSave($scope.cert).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
  
  $scope.selectLevelType = function(type){
    $scope.cert.type = type;
    $scope.cert.uRole = "2";
  };
  
  $scope.selectRoleResult = function(){
    if ($scope.cert.uRole == "99"){
      $scope.cert.type = "";
    }
  }
  
  $scope.export = function(){
    exportService.exportCSV($scope.config,"FA_LIST_EXPORT");
  };


  $scope.setPageSize = $scope.config.pageSize;

  $scope.changePageSize = function(){
    if(!$scope.setPageSize){
      alert('不为空且最大不超过1000');
      $scope.setPageSize = $scope.config.pageSize;
    }else{
      $scope.config.pageSize = $scope.setPageSize;
    }
  };
  if ($scope.dictMap.roleMapModel[0].value != 'Y') $scope.dictMap.roleMapModel.unshift({value:"Y",text:"认证已通过"});
  console.info('注册来源活动');
  function getactSource(){
    faService.queryActSource().then(function(json){
        console.info(json);
        $scope.actSourceList = json.list;
    });
  }
  getactSource();


}]);

faApp.controller('FaAddCtrl',['$scope','faService','$location','$controller',function($scope,faService,$location,$controller) {   
  $controller('BaseCtrl', {$scope: $scope}); 
}]);

faApp.controller('FaViewCtrl',['$rootScope','$scope','faService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,faService,$location,$controller,$routeParams,$route,$cookies,$timeout,$filter) {

  $controller('BaseCtrl', {$scope: $scope});

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.visit = {};
  $scope.loading = true;
  $scope.auditOptionMessage = "";
  $scope.aoMsg = false;
  $scope.firstReturnVisitCycle = "";
  $scope.stayAwayFromTheLastVisit = "";

  var myKeHuNow = angular.fromJson($cookies.myKeHuNowPageListSize);

  $scope.listWhere="?newPage=true";
  $scope.vtype="";
  if($routeParams.orderFlag=="1"&&$routeParams.notHasVisit){
    $scope.vtype="成交客户列表";
  }else if($routeParams.orderFlag=="2"&&$routeParams.notHasVisit){
    $scope.vtype="待沉寂理财师列表";
  }else if($routeParams.notHasVisit){
     $scope.vtype="待回访理财师列表";
  }else if($routeParams.notHasCheck){
     $scope.vtype="待审核理财师列表";
  }else if($routeParams.isnoManagerUserLicaishi){
     $scope.vtype="待分配理财师列表";
  }else{
    $scope.vtype="所有理财师列表";
  }
  if($routeParams.isnoManagerUserLicaishi){//待分配
    $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
  }
  if($routeParams.notHasVisit){//是否回访
    $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
  }
  if($routeParams.notHasCheck){//待审核
    $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
  }
  if($routeParams.orderFlag){//是否交易    1 成交客户
    $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
  }
  if($routeParams.systemUserId){//当前用户ID  我的客户列表
    $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
  }
  if($routeParams.pageNo){//当前用户ID  我的客户列表
    $scope.listWhere=$scope.listWhere+"&pageNo="+$routeParams.pageNo;
  }
  $scope.$watch('id',function(){
    for(m in myKeHuNow){
      if( myKeHuNow[m] == $scope.id ){
        $scope.now = m;
      }
    }
    faService.faQuery({id:$scope.id}).then(function(json){
      $scope.item = json.faUserInfo || {};
      $scope.loading = false;
      /**基本 属性**/
      if($scope.item.sourceCode =="")  $scope.item.sourceCode="--";
      if($scope.item.sourceLoginName =="")  $scope.item.uManagerId="--";
      // $scope.item.uManagerId = $scope.item.uManagerId=0 || "--";
      if($scope.item.uManagerId==0) $scope.item.uManagerId="--";


      /**审核 属性**/
      $scope.cert.uCompanyName = $scope.item.uCompanyName || "";
      $scope.cert.uCompanyADD = $scope.item.uCompanyADD || "";
      $scope.cert.uJob = $scope.item.uJob || "";
      $scope.cert.uRole = $scope.item.uRole ;
      $scope.cert.type = $scope.cert.uRole;
      $scope.cert.uRealName = $scope.item.uRealName || "";
      if($scope.item.faUserauth){
        $scope.cert.wechatNo = $scope.item.faUserauth.wechatNo || "";
      }
      if($scope.item.uRole!="99"){
        $scope.cert.uRole ="2";
      }
      $scope.cert.uAuditOpinion=$scope.item.uAuditOpinion ;
      if($scope.item.uRole=="99"&&$scope.cert.uAuditOpinion!="注册手机号码与名片手机号码不一致"&&$scope.cert.uAuditOpinion!="未上传名片或上传名片与资质要求不符"){
        $scope.auditop.auditOptionMessage=$scope.cert.uAuditOpinion;
        $scope.cert.uAuditOpinion="3";
        $scope.aoMsg=true;
      }
      $scope.cert.uSex = $scope.item.uSex;
      $scope.cert.uEmail = $scope.item.uEmail || "";
      $scope.cert.auditRemarks = $scope.item.auditRemarks || "";

      /**回访 属性**/
      $scope.visit.faId = $scope.item.id;
      $scope.visit.id = $scope.item.id;
      $scope.visit.uRealName = $scope.item.uRealName || "";
      $scope.visit.uMobile = $scope.item.uMobile || "";

      $scope.visit.uCompanyName = $scope.item.uCompanyName || "";
      $scope.visit.uAddress = $scope.item.uAddress || "";
      $scope.visit.uJob = $scope.item.uJob || "";
      $scope.visit.uEmail = $scope.item.uEmail || "";
      $scope.visit.uSex = $scope.item.uSex;


      if($scope.item.faUserauth){
        $scope.visit.otherContactInfo = $scope.item.faUserauth.otherContactInfo || "";
        $scope.visit.wechatNo = $scope.item.faUserauth.wechatNo || "";
        $scope.visit.customerHeat = $scope.item.faUserauth.customerHeat || "";
        $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
        $scope.visit.customerStage = $scope.item.faUserauth.customerStage || "";
        $scope.visit.customerKnowledge = $scope.item.faUserauth.customerKnowledge || "";
        $scope.visit.customerSource = $scope.item.faUserauth.customerSource || "";
        $scope.visit.customerLable = $scope.item.faUserauth.customerLable || "";
        $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
      }
      $scope.firstReturnVisitCycle = diffTime($scope.item.licaishiVO.createDate,$scope.item.visitStatisticVO.firstReturnVisitTime);
      $scope.stayAwayFromTheLastVisit = diffTime($scope.item.visitStatisticVO.latestVisitTime,$scope.item.visitStatisticVO.systemDate);
      // $scope.selectLevelType($scope.cert.uRole);
    });

    faService.faUserVisit($scope.id).then(function(json){
      $scope.visitList = json.list;
    });
  },true)
  //faService.faQuery({id:$scope.id}).then(function(json){
  //  $scope.item = json.faUserInfo || {};
  //  $scope.loading = false;
  //  /**基本 属性**/
  //  if($scope.item.sourceCode =="")  $scope.item.sourceCode="--";
  // if($scope.item.sourceLoginName =="")  $scope.item.uManagerId="--";
  // // $scope.item.uManagerId = $scope.item.uManagerId=0 || "--";
  // if($scope.item.uManagerId==0) $scope.item.uManagerId="--";
  //
  //
  //  /**审核 属性**/
  //  $scope.cert.uCompanyName = $scope.item.uCompanyName || "";
  //  $scope.cert.uCompanyADD = $scope.item.uCompanyADD || "";
  //  $scope.cert.uJob = $scope.item.uJob || "";
  //  $scope.cert.uRole = $scope.item.uRole ;
  //  $scope.cert.type = $scope.cert.uRole;
  //  $scope.cert.uRealName = $scope.item.uRealName || "";
  //  if($scope.item.faUserauth){
  //    $scope.cert.wechatNo = $scope.item.faUserauth.wechatNo || "";
  //  }
  //  if($scope.item.uRole!="99"){
  //    $scope.cert.uRole ="2";
  //  }
  //   $scope.cert.uAuditOpinion=$scope.item.uAuditOpinion ;
  //  if($scope.item.uRole=="99"&&$scope.cert.uAuditOpinion!="注册手机号码与名片手机号码不一致"&&$scope.cert.uAuditOpinion!="未上传名片或上传名片与资质要求不符"){
  //    $scope.auditop.auditOptionMessage=$scope.cert.uAuditOpinion;
  //    $scope.cert.uAuditOpinion="3";
  //    $scope.aoMsg=true;
  //  }
  //  $scope.cert.uSex = $scope.item.uSex;
  //  $scope.cert.uEmail = $scope.item.uEmail || "";
  //  $scope.cert.auditRemarks = $scope.item.auditRemarks || "";
  //
  //  /**回访 属性**/
  //  $scope.visit.faId = $scope.item.id;
  //  $scope.visit.id = $scope.item.id;
  //  $scope.visit.uRealName = $scope.item.uRealName || "";
  //  $scope.visit.uMobile = $scope.item.uMobile || "";
  //
  //  $scope.visit.uCompanyName = $scope.item.uCompanyName || "";
  //  $scope.visit.uAddress = $scope.item.uAddress || "";
  //  $scope.visit.uJob = $scope.item.uJob || "";
  //  $scope.visit.uEmail = $scope.item.uEmail || "";
  //  $scope.visit.uSex = $scope.item.uSex;
  //
  //
  //  if($scope.item.faUserauth){
  //      $scope.visit.otherContactInfo = $scope.item.faUserauth.otherContactInfo || "";
  //      $scope.visit.wechatNo = $scope.item.faUserauth.wechatNo || "";
  //      $scope.visit.customerHeat = $scope.item.faUserauth.customerHeat || "";
  //      $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
  //      $scope.visit.customerStage = $scope.item.faUserauth.customerStage || "";
  //      $scope.visit.customerKnowledge = $scope.item.faUserauth.customerKnowledge || "";
  //      $scope.visit.customerSource = $scope.item.faUserauth.customerSource || "";
  //      $scope.visit.customerLable = $scope.item.faUserauth.customerLable || "";
  //      $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
  //  }
  //  $scope.firstReturnVisitCycle = diffTime($scope.item.licaishiVO.createDate,$scope.item.visitStatisticVO.firstReturnVisitTime);
  //  $scope.stayAwayFromTheLastVisit = diffTime($scope.item.visitStatisticVO.latestVisitTime,$scope.item.visitStatisticVO.systemDate);
  //  // $scope.selectLevelType($scope.cert.uRole);
  //});

  $scope.isShowVisitLayer = false;
  $scope.isShowCheckFaUser = false;
  $scope.visitList = [];



  /**回访**/
  $scope.showVisitLayer = function(id,mobile,mediaSource,isValid){
    faService.faUserVisit($scope.id).then(function(json){
      $scope.visitList = json.list;
    });
    $scope.isShowVisitLayer = true;
  }
  /**审核**/
  $scope.checkFaUser = function(id,mobile,mediaSource,isValid){

    $scope.isShowCheckFaUser = true;
  }
  //下一页上一页

  $scope.faItem = function (f) {
    for(m in myKeHuNow){
      if( myKeHuNow[m] == $scope.id ){
        $scope.now = m;
      }
    }
    if(f == 'next'){
      $scope.id = myKeHuNow[$scope.now-0+1];

    }else if(f == 'prev') {
      $scope.id = myKeHuNow[$scope.now-1];
    }
    $location.url("/fa/view?id="+$scope.id+$rootScope.viewNextBtn.listWhere+'&pageNo='+$rootScope.viewNextBtn.pageNo);
  }
  // 动态显示三方公司
  $scope.sfCompanyList = {};
  $scope.isShowSelectCompany = false;
  $scope.isNewCompany = false;
  $scope.newCompanyName = '';

  $scope.showSanfangCompany = function(name){
    $scope.isNewCompany = false;
    if(name){
      // 根据name查询列表
      if(name.length >= 2){
        faService.sanfangQuery({keyWord: name}).then(function(json){
          $scope.sfCompanyList = json.list;
          if(json && $scope.sfCompanyList.length <= 0){
            $scope.isNewCompany = true;
            $scope.newCompanyName = name;
            $scope.isShowSelectCompany = false;
          }else{
             $scope.isShowSelectCompany = true;
          }
        });
      }
    }else{
      $scope.isShowSelectCompany = false;
    }
  }
  $scope.selectedSanfangCompany = function(name, t){
    $scope.isShowSelectCompany = false;
    if(t){
      $scope.visit.uCompanyName = name;
    }else{
      $scope.cert.uCompanyName = name;
    }
  }

  $scope.addFaUserVisit = function(){
    if ($scope.visitform.$invalid){
       alert("请先完整填写信息");
      return;
    }

    /**先提交 基本信息**/
    faService.faUserVisitDetailAdd($scope.visit).then(function(json){
      if (!json.statusCode){
        if($scope.isNewCompany && $scope.newCompanyName){
          faService.sanfangAdd({tpcFullName: $scope.newCompanyName}).then(function(json){
            console.log(json);
          });
        }

        $scope.addAlert("操作成功");
        //$route.reload();
        $location.path('fa/view').search({id:$scope.id})
      }else{
        alert("出错了:" + json.statusCode);
      }
    });

    /**再提交 回访信息**/
    faService.faUserVisitAdd({faId : $scope.id, remark : $scope.visitRemark}).then(function(json){
      if (!json.statusCode){
        faService.faUserVisit($scope.id).then(function(json){

          $scope.visitList = json.list;
        });
        $scope.visitRemark = "";
      }else{
        alert("出错了:" + json.statusCode);
      }
    });
  }

  $scope.faUserVisitUpdate = function(a){
    if(a != undefined && a != ""){
      faService.faUserVisitUpdate({faId : $scope.id, adValid : a}).then(function(json){
        if (!json.statusCode){
          alert("修改成功！");
        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请选择有效性！");
    }
  }

  $scope.black = {blackType:1};
  $scope.showBlackAddForm = function(){
    $scope.black.userId = $scope.id;
    $scope.showBlackAddFormFlag = true;
  };

  $scope.blackAdd = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.alertNextPage("操作成功");
          $location.path("/fa/list");
        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
  diffTime = function (startDate,endDate) {
    var diff=endDate - startDate;//时间差的毫秒数
    if(startDate==null || endDate ==null ||diff <0){
      return "--";
    }

    //计算出相差天数
    var days=Math.floor(diff/(24*3600*1000));

    //计算出小时数
    var leave1=diff%(24*3600*1000);    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000));
    //计算相差分钟数
    var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000));

    //计算相差秒数
    var leave3=leave2%(60*1000);      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000);

    var returnStr = seconds + "秒";
    if(minutes>0) {
      returnStr = minutes + "分" + returnStr;
    }
    if(hours>0) {
      returnStr = hours + "小时" + returnStr;
    }
    if(days>0) {
      returnStr = days + "天" + returnStr;
    }
    return returnStr;
  }

  $scope.cert = {};
  $scope.auditop={};
  $scope.certSave = function(){
    $scope.cert.id = $scope.id

    if (!$scope.certform.$invalid){
      if ($scope.cert.type && $scope.cert.uRole != "99" && $scope.cert.uRole != "98"){
        $scope.cert.uRole = $scope.cert.type;
      }
      if (!$scope.cert.uRole || ($scope.cert.uRole == "2" && (!$scope.cert.type||$scope.cert.type=='98'))){
        alert("请选择评级");
        return;
      }
      if($scope.aoMsg&&$scope.cert.uRole == 99){
        if(!$scope.auditop.auditOptionMessage){
          alert("请填写未通过原因！");
          return;
        }
        $scope.cert.uAuditOpinion = $scope.auditop.auditOptionMessage;
      }

      faService.certSave($scope.cert).then(function(json){
        if (!json.statusCode){
          if($scope.isNewCompany && $scope.newCompanyName){
            faService.sanfangAdd({tpcFullName: $scope.newCompanyName}).then(function(json){
              console.log(json);
            });
          }

          $scope.addAlert("操作成功");
          $route.reload();
          //$location.url("/fa/view?id="+$scope.id);
          //$route.reload();

        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };

  $scope.selectLevelType = function(type){
    $scope.cert.type = type;
    $scope.cert.uRole = "2";
  };
  $scope.selectCustomerLable = function(type){
    $scope.visit.customerLable = type;
  };
  $scope.selectRoleResult = function(){
    if ($scope.cert.uRole == "99"){
      $scope.cert.type = "1";
      $scope.cert.uAuditOpinion="";
    }else{
      $scope.cert.type = "";

    }
  };

  $scope.auditOption = function(){
    if($scope.cert.uAuditOpinion == "3"){
      $scope.aoMsg = true;
    }else{
      $scope.aoMsg = false;
    }
  };

  $scope.isShowSaveUpload = false;
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.uCardAddress = response.attribute.fileUrl;
        $scope.isShowSaveUpload = true;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

  $scope.saveUpload = function(){
    if (!$scope.item.uCardAddress){
      alert("请先上传图片");
      return;
    }
    delete $scope.item.lastLoginTime;
    faService.certSaveImg($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        alert("保存成功");
        $scope.cert.uRole="98";
      }
    });
  };

  $scope.companyInvitationCode = "";
  $scope.markFaUser = function(){
    if($scope.id){
      faService.markFaUser($scope.id).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.companyInvitationCode = json.cic;
          alert("标记成功！");
        }
      });
    }else{
      alert("系统异常，请刷新页面重试！");
    }
  }
  //待办和发送短信
  console.info('待办和发送短信');
  $scope.sendMsgData = {};
  $scope.sendMessage = function(){
    //faRevisitType;//类型1发送短信2待办
    if($scope.sendMsgData.faRevisitType == 1){
      $scope.sendMsgData.faRevisitDate = undefined;
    }else {
      $scope.sendMsgData.faRevisitPhone = undefined;
      $scope.sendMsgData.faRevisitDate = $filter("date")($scope.sendMsgData.faRevisitDate,"yyyy-MM-dd HH:mm");
    }
    ////关联理财师id
    $scope.sendMsgData.faRevisitUserId =  $scope.item.id;
    var codeMap = {
      '2002':'参数缺失',
      '4013':'时间要大于当前时间'
    };
    faService.revisiitTask($scope.sendMsgData).then(function(json){
        console.log(json);
        if (json.statusCode){
          alert("操作失败:" + codeMap[json.statusCode]);
        }else{
          $scope.sendMsgData.faRevisitContent = '';
          $scope.isShowMsgVariable = false;
          alert("操作成功！");


        }

    });
  };

  $scope.ckSendMessage  = function(type){
    $scope.isShowMsgVariable = true;
    $scope.sendMsgData.faRevisitType = type;

  }


}]);

faApp.controller('FaBlackListCtrl',['$scope','faService','$location','$controller',function($scope,faService,$location,$controller) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.blacks = {};

  $scope.$watch('config',function(){
    faService.blackList($scope.config).then(function(json){
      $scope.blacks = json.list || [];
      $scope.pager = json.pager;
    });
  },true);

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "loginName" : '',
  };

  $scope.searchMap = {
    "loginName" : '',
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };

  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };

}]);

faApp.controller('FaBlackViewCtrl',['$scope','faService','$location','$controller','$routeParams','$window',function($scope,faService,$location,$controller,$routeParams,$window) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.black = {blackType:2,userId:$scope.id};
  $scope.detail = {};
  $scope.blackHistorys = [];
  $scope.whiteHistorys = [];

  $scope.showDeleteForm = function(){
    $scope.showDeleteFormFlag = true;
    $window.scrollTo(0,0);
  };

  faService.blackQuery($scope.id).then(function(json){
    $scope.detail = json.dto;
    angular.forEach(json.list,function(o){
      if (o.blackType == "1")$scope.blackHistorys.push(o); 
      else $scope.whiteHistorys.push(o);
    });
  });

  $scope.blackDelete = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.alertNextPage("移除操作成功");
          $location.path("/fa/blacklist");
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
}]);

faApp.controller('FaSbdstatCtrl',['$scope','faService','$location','$controller','$route','exportService','$routeParams',function($scope,faService,$location,$controller,$route,exportService,$routeParams) {   
  $scope.ctrlName = "FaSbdstatCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.fas = [];

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sbdstat($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true); 
 
  $scope.export = function(){
    exportService.exportCSV($scope.config,"FA_SBD_EXPORT");
  }; 
 

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['createDate'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"authPassCount":["desc","asc"],"createDate":["desc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  }; 
}]);

faApp.controller('FaSbdDetailCtrl',['$scope','faService','$location','$controller','$route','$routeParams',function($scope,faService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.fas = [];

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sbddetail($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true);

  $scope.config = {
    "pageSize" : 100,
    "pageNo" : 1,
    "uLoginName" : '',
    "sourceCode" : $routeParams.id
  };

  $scope.searchMap = {};

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    
    $scope.config.pageNo = 1;

  };
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };  
  
}]);

faApp.controller('SanFangCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sanfangQuery($scope.config).then(function(json){
        $scope.list = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true);

  $scope.sfDelete = function(id){
    if(id){
      if(confirm('确认要删除吗！')){
        faService.sanfangDelete(id).then(function(json){
          $route.reload();
        });
      }
    }else{
      alert('有问题，请刷新页面重试！');
    }
  }

  $scope.isShowUpdateLayer = false;
  $scope.sf = {};


  $scope.toUpdate = function(id){

    if(id){
      $scope.tpcCommoyType = {};
      $scope.isShowUpdateLayer = true;
      $scope.sf.id = id;

      angular.forEach($scope.list, function(o){
        if(o.id == id){
          $scope.sf.tpcFullName = o.tpcFullName;
          $scope.sf.tpcAbbrLetter = o.tpcAbbrLetter;
          $scope.sf.tpcShortName = o.tpcShortName;
          if(o.tpcCompanyProperty!=undefined){
            angular.forEach(o.tpcCompanyProperty.split(","),function(i){
              $scope.tpcCommoyType[i] = true;
            });
          }
        }
      });
    }else{
      alert('有问题，请刷新页面重试！');
    }
  }

  $scope.sfUpdate = function(){
    if($scope.sf){
      if(!$scope.sf.id){
        alert('有问题，请刷新页面重试！');
        return;
      }
      if(!$scope.sf.tpcFullName){
        alert('请填写公司全称');
        return;
      }
      if(!$scope.sf.tpcShortName){
        alert('请填写公司简称');
        return;
      }
      if(!$scope.sf.tpcAbbrLetter){
        alert('请填写拼音缩写');
        return;
      }else if($scope.sf.tpcAbbrLetter.length < 2){
        alert('拼音缩写长度必须大于两位');
        return;
      }
      if($scope.tpcCommoyType){
        var w = [];
        for(m in $scope.tpcCommoyType){
          if($scope.tpcCommoyType[m]){
            w.push(m);
          }
        }
        $scope.sf.tpcCompanyProperty = w.join(',');
        console.log($scope.sf.tpcCompanyProperty);
      }
      //return;
      faService.sanfangUpdate($scope.sf).then(function(json){
        $route.reload();
      });
    }
  }
}]);

faApp.controller('DownListCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams',function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.isShowSaveUpload = false;
  $scope.uplpader = false;
  $scope.infoContent = false;
  $scope.isStartUpload = false;

  $scope.searchMap = {};
  $scope.search = function(notsave) {
      angular.forEach($scope.searchMap, function(o, i) {
        $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
      });
  }
  $scope.startUpload = function() {
    $scope.isStartUpload = true;
    faService.downLineUpFileload($scope.fileUrl).then(function(json){
      if(json.statusCode) {
        alert('出错了' + json.statusCode)
      }else{
        alert('导入成功');
        $scope.isShowSaveUpload = false;
        $scope.infoContent = false;
        $scope.isStartUpload = false;
        $route.reload();
      }
    })
}
  $scope.chkdownlineAll = function(){
    if($("#chkdownlineAll").attr("checked") == "checked"){
      $("[name='chkdownline']").attr("checked","checked");
    }else{
      $("[name='chkdownline']").attr("checked",false);
    }
  }
  $scope.delAll = function(){
    var allCheck = $("[name='chkdownline']");
    var ids = "";
    $("[name='chkdownline']").each(function(){
      if($(this).attr("checked") == "checked"){
          ids += $(this).val() + ",";
        }
    });
     if(ids.length > 0){
      if(!confirm("确认更新吗?")){
        return;
      }
      ids = ids.substring(0, ids.length - 1);
        var i={
          'ids':ids,
          'deleteTag':2
        };
      faService.downLineUpdata(i).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("删除成功！");
         $route.reload();
        }
      });
    }else{
      alert("请选择一个对象删除！");
    }
  }
  $scope.del = function(id) {
  var i={
    'id':id,
    'deleteTag':2
  };
  if(confirm("确认删除吗？")){
         faService.downLineUpdata(i).then(function(json){
        if(json.statusCode) {
          alert('删除失败' + json.statusCode)
        }else{
          alert('删除成功');
           $route.reload();
        }
      })
  }

  }
  $scope.$watch('config',function(){
    faService.downLineList($scope.config).then(function(json){ 
      $scope.list = json.list || [];
      $scope.pager = json.pager;
    });
  },true);

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onUpload: function (fileName) {
      $scope.isShowSaveUpload = true;
      $scope.uplpader = true;
    },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.uplpader = false;
        $scope.fileUrl = response.attribute.fileUrl;
        faService.downLineUpFile($scope.fileUrl).then(function(json){ 
          if(json.statusCode == '0003') {
            $scope.isShowSaveUpload = false;
            alert('上传文件无法识别，请按模板填写后重新上传')
          }else{
            $scope.isShowSaveUpload = true;
            $scope.infoContent = true;
            $scope.uploadList = json.list  || [];
          }
        });
      } else { 
        alert('上传文件无法识别，请按模板填写后重新上传'); 
      }
    }    
  });

}]);

faApp.controller('DownViewCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $scope.id = $routeParams.id || '';
  $scope.edit = $routeParams.edit || false; //是否编辑
  $scope.item = {};
  $scope.showBlackAddFormFlag = false;

  if($scope.id) {
    faService.downLineDetail($scope.id).then(function(json){
      $scope.item = json.bean || [];
    })
  }
  $scope.save = function(){
    if($scope.form.$invalid){
      alert('请正确填写必填项（带*项）')
      return;
    }else if($scope.showBlackAddFormFlag){

      faService.downLineAdd($scope.item).then(function(json){
        if(json.statusCode) {
          alert('出错了' + json.statusCode)
        }else{
          alert('添加成功');
          $location.path('/fa/downline/list');
        }
      })
      $scope.showBlackAddFormFlag = false; 
    }else{
      $scope.showBlackAddFormFlag = true;
    }  
  }
  $scope.upData = function(){
    $scope.item.id = $scope.id;
    if($scope.form.$invalid){
      alert('请正确填写必填项（带*项）')
      return;
    }else{      
      faService.downLineUpdata($scope.item).then(function(json){
        if(json.statusCode) {
          alert('出错了' + json.statusCode)
        }else{
          alert('修改成功');
          $location.path('/fa/downline/list');
        }
      })     
    }
  }
}]);
faApp.controller('LcsmanlistCtrl', ['$scope','faService','$location','$controller','$route','exportService','licaishiManagerService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,licaishiManagerService,$routeParams) {
   
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.isShowDetail=false;

    $scope.config={
        "pageSize" : 50,
    "pageNo" : 1,
    };
    $scope.currentLoginId="";
    if($scope.loginStatus.loginName!='admin'){
      $scope.currentLoginId=$scope.loginStatus.id;
    }
    if(!$scope.config.systemUserId){
      $scope.config.systemUserId=$scope.currentLoginId;
    }
    $scope.item={};
    $scope.itemDetail={};
     $scope.$watch('config',function(){
      var c=$scope.config;
      if(c.endDate&&c.startDate&&c.endDate<c.startDate){
        alert("开始时间必须小于等于结束时间!");
        return;
      }
      if(c.endDate){
        if(c.endDate.length<18){//修改参数  避免多次调用  config变动
          c.endDate=c.endDate+" 23:59:59";
        }else{
          console.log("调用过了");
          return ;
        }
      }
      faService.lcsmanList(c).then(function(json){
        $scope.item = json.list || [];
      });
       faService.lcsmanDetailList(c).then(function(json){
        $scope.itemDetail = json.list || [];
        $scope.pager=json.pager;
      });
    },true);
   
    $scope.managerParam={"pageSize" : 10000};
    //如果是admin 查询全部
    if($scope.loginStatus.loginName=='admin'){
      licaishiManagerService.list($scope.managerParam).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.licaishiManagerUserList = json.list;
            $scope.loading = false;
          }
        });
    }else{
       licaishiManagerService.otherList($scope.managerParam).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList = json.list;
          $scope.loading = false;
        }
      });
    }
   

    $scope.export = function(v){
      if(v==1){
        exportService.exportCSV($scope.config,"LCS_MAN_DETAIL_CSV");
        return ;
      }
      exportService.exportCSV($scope.config,"LCS_MAN_STATICTICS_CSV");
    };


  $scope.config.setPageSize = $scope.config.pageSize;
  $scope.changePageSize = function(){
      if(!$scope.config.setPageSize){
        alert('不为空且最大不超过1000');
        $scope.setPageSize = $scope.config.pageSize;
      }else{
        $scope.config.pageSize = $scope.config.setPageSize;
      }
    };
}]);


faApp.controller('NewOrderCWAViewCtrl',['$scope','newOrderService','$location','$controller','$route','$routeParams','$filter',function($scope,newOrderService,$location,$controller,$route,$routeParams,$filter) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.m = $routeParams.m;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {'id':$scope.id};
  $scope.pType=$routeParams.pType;
  newOrderService.queryCWOrderXiangqing({'id':$scope.id,"orderCtrType":$scope.m}).then(function(json){
    $scope.item = json.orderDetail|| {};
    console.log($scope.item.frontProfitAmount);
    console.log($scope.item.allProfitAmount);
    $scope.loading = false;
    
  });
    


}]); 


faApp.controller('FinancierListCtrl', ['$scope', 'financierService', '$location', '$controller', '$route', function($scope, financierService, $location, $controller, $route) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.config = {
    "pageSize": 20,
    "pageNo": 1
  };

  $scope.$watch('config', function() {
    financierService.financierList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
    });
  }, true);  

  $scope.delete = function(id){
    if(id && confirm("确定要删除吗")){
      financierService.financierDelete({id: id}).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          alert("删除成功");
          $route.reload();
        }
      });
    }
  }
}]);

faApp.controller('FinancierAddCtrl', ['$scope', 'financierService', '$location', '$controller', '$route', function($scope, financierService, $location, $controller, $route) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.financier = {};

  $scope.save = function(){
    if (!$scope.form.$invalid){
      financierService.financierAdd($scope.financier).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          alert("添加成功");
          $location.path("/financier/list");
        }
      });
    }
  };
}]);
faApp.controller('FissListCtrl',['$scope','fissService','$location','$controller','$routeParams','$filter',function($scope,fissService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.code = $routeParams.code;

  //所有列的映射
  $scope.allColMap = {
    "3066":{ "prodID":"信托产品ID", "prodName":"信托产品名称", "trustCompanyName":"信托公司", "trustCompanyID":"信托公司ID", "depositOrg":"信托产品公告", "publicArea":"发行区域", "investTerm":"信托方式", "investField":"投资领域", "targetSize":"标规模", "foundMoney":"投资币种", "recommendBDate":"募集起始日", "recommendEDate":"募集终止日", "foundDate":"成立日期", "closeTime":"封闭期", "currency":"投资币种", "buyMoney":"产品起购金额", "manageFee":"固定管理费", "yieldUp":"预期收益上限", "yieldDown":"预期收益下限", "fundsUseWay":"资金运用方式", "ensureWay":"追加认购递增金额", "incomeDesc":"预期收益率", "trustQuit":"信托退出方式", },
    "2059":{ "FUNDCODE":"基金代码", "PRICEDATE":"价格日期", "NETVALUE":"最新净值", "TOTALVALUE":"累计净值", "TOTALBONUS":"累计分红", "BONUSDATE":"最近分红日期", "BONUSTIMES":"累计分红次数", "INCREASE_DAY":"日增长率", "INCREASE_WEEK":"周增长率", "INCREASE_MONTH":"月增长率", "INCREASE_YEAR":"年增长率", "INCREASE_CREATE":"成立以来增长率", "INCREASE_QUARTER":"季度增长率", "MRNLEVEL":"晨星评级", "FUNDSTATUS":"基金状态", },
  };

  //所有表头的映射
  $scope.allHeaderMap = {
    "3066":[{f:"prodID",w:100},{f:"prodName",w:100},{f:"trustCompanyName",w:100},{f:"publicArea",w:100},{f:"investTerm",w:100},{f:"investField",w:100},{f:"targetSize",w:100},{f:"recommendBDate",w:100},{f:"recommendEDate",w:100}],
    "2059":[ {f:"FUNDCODE",w:100}, {f:"PRICEDATE",w:100}, {f:"NETVALUE",w:100}, {f:"TOTALVALUE",w:100}, {f:"TOTALBONUS",w:100}, {f:"BONUSDATE",w:100}, {f:"BONUSTIMES",w:100}, {f:"INCREASE_DAY",w:100}, {f:"INCREASE_WEEK",w:100}, {f:"INCREASE_MONTH",w:100}, {f:"INCREASE_YEAR",w:100}, {f:"INCREASE_CREATE",w:100}, {f:"INCREASE_QUARTER",w:100}, {f:"MRNLEVEL",w:100}, {f:"FUNDSTATUS",w:100}, ],
  };

	$scope.$watch('config',function(){
    fissService.fissList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;

      angular.forEach($scope.list,function(o,j){
        for (var i in o){
          if (i == 'recommendEDate' || i == 'recommendBDate'){ o[i] = $filter("date")(o[i],"yyyy-MM-dd"); }
          else if (i == 'investField' ){ o[i] = $filter("fissInvestTypeRender")(o[i]); }
        }  
      });
    });
  },true);

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
		"code" : $scope.code || "",
	};
}]);

faApp.controller('FollowUpCtrl',['$scope','folllowUpService','$location','$controller','$route',function($scope,folllowUpService,$location,$controller,$route) {
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      folllowUpService.list($scope.config).then(function(json){
        $scope.list = json.list;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  },true)


	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
    "oType":"02"
	};

	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  $scope.searchMap = {};

  $scope.search = function(){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    $scope.config.pageNo = 1;
  };

 $scope.chooseOrderId = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";
  $scope.orderList = [];
  
    //点击事件
$scope.changeShowOrderManagerLayer=function(){
  $scope.isShowOrderManagerLayer = true;
  folllowUpService.queryOrderList().then(function(json){
    $scope.orderList=json.list;
  });

}

}]);


faApp.controller('FollowUpViewCtrl',['$scope','folllowUpService','$location','$controller','$route','$routeParams',function($scope,folllowUpService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {'status':'02','id':$scope.id};

  folllowUpService.query({id:$scope.id}).then(function(json){
    if (json.list.length){
      $scope.item = json.list[0] || {};
      $scope.item['faInfo']['faShowName'] = $scope.item.faInfo.uName || $scope.item.faInfo.uRealName || $scope.item.faInfo.uLogin;
    }
    $scope.loading = false;
    
  });
  
  $scope.save = function(id){
    folllowUpService.edit($scope.review).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $location.path("/order/followUp/simu/list");
      }
    });
  };
 
}]);



faApp.controller('FpAccountVoucherCtrl', ['$cookieStore','$scope','$routeParams','$location','productService','fpAccountVoucherService', '$controller', function($cookieStore,$scope,$routeParams, $location,productService,fpAccountVoucherService, $controller) {
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.showFullName = function(){
      // 根据name查询列表
       var pName= $scope.querypFullName==undefined?'':$scope.querypFullName;

      productService.queryAllProductByFullName({'pName':pName}).then(function(json){
        $scope.productFullName = json.map;
        $scope.loading = false;
      });
  }

  $scope.showAllExistingAccount = function(){
     var fundAccountName= $scope.queryExistingAccount==undefined?'':$scope.queryExistingAccount;

      fpAccountVoucherService.queryAllExistingAccount({'fundAccountName':fundAccountName}).then(function(json){
        $scope.allExistingAccount = json.map;
        $scope.loading = false;
      });
  }
  $scope.config = {"pageSize": 20,
    "pageNo": 1};
  $scope.search = function(){
    //查询凭条列表
    fpAccountVoucherService.listFpAccountVoucher($scope.config).then(function(json){
      $scope.accountVoucherList = json.list;
      $scope.pager=json.pager;
      $scope.loading = false;
    });
  }

  $scope.$watch('config',function(){
    $scope.search();
  },true);

  fpAccountVoucherService.queryAccountVoucherCreateBy({}).then(function(json){
    $scope.accountVoucherCreateBy = json.map;
    $scope.loading = false;
  });
 
  $scope.showFullName();
  $scope.showAllExistingAccount();
  $scope.search();
}]);



faApp.controller('FpAccountVoucherDetailCtrl', ['$cookieStore','$scope','$routeParams','$location','$route','productService','fpAccountVoucherService', '$controller', function($cookieStore,$scope,$routeParams, $location,$route,productService,fpAccountVoucherService, $controller) {
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.accountVoucher={};

  $scope.productInfo =[{}];
  $scope.isShowExistingAccount=false;

  $scope.id=$routeParams.id;
  if($scope.id){
     fpAccountVoucherService.detailFpAccountVoucher({'id':$scope.id}).then(function(json){
        $scope.accountVoucher = json.dto;
         $scope.productInfo=$scope.accountVoucher.fpAccountVoucherProductList;
         //区分
         angular.forEach($scope.productInfo,function(o,i){
          if($scope.productInfo[i].accountType.indexOf("1")!=-1){
            $scope.productInfo[i].sale='0';
          }
          if($scope.productInfo[i].accountType.indexOf("2")!=-1){
            $scope.productInfo[i].tiexi='0';
          }
          if($scope.productInfo[i].accountType.indexOf("3")!=-1){
            $scope.productInfo[i].buxi='0';
          } 
           $scope.showFullName(i);
        });
        console.log( $scope.accountVoucher);
        $scope.loading = false;
      });
  }


  $scope.showFullName = function(v,queryName){
      // 根据name查询列表
      var pName= queryName==undefined?'':queryName;
      productService.queryAllProductByFullName({'pName':pName}).then(function(json){
        $scope.productInfo[v].productFullName = json.map;
        console.log($scope.productInfo[v].productFullName);
        $scope.loading = false;
      });
  }

  $scope.showAllExistingAccount = function(){

     var accountName= $scope.accountVoucher.fundAccountName==undefined?'':$scope.accountVoucher.fundAccountName;
      if(!accountName){
         $scope.isShowExistingAccount=false;
        return ;  
      }
      fpAccountVoucherService.queryAllExistingAccount({'fundAccountName':accountName}).then(function(json){
        $scope.allExistingAccount = json.map;
        if(JSON.stringify( $scope.allExistingAccount) != "{}"){
           $scope.isShowExistingAccount=true;
        }else{
          $scope.isShowExistingAccount=false;
        }
        console.log( $scope.allExistingAccount);
        $scope.loading = false;
      });
  }
   
 
  $scope.isShowExistingAccountClick = function(v){
    $scope.accountVoucher.fundAccountName=v;
    $scope.isShowExistingAccount=false;
  }


  $scope.showFullName(0);



  $scope.save = function(){
    if($scope.form.$invalid){
      alert("填写完整表单!");
      return;
    }
    console.log($scope.productInfo);
    var isEnd=false;
    angular.forEach($scope.productInfo,function(o,i){
        var sale=$scope.productInfo[i].sale;
        var tiexi=$scope.productInfo[i].tiexi;
        var buxi=$scope.productInfo[i].buxi;
        var code=$scope.productInfo[i].productCode;
        var value="";
        if(sale=="0"){
          value+="1";
        }
        if(tiexi=="0"){
          value+="2";
        }
        if(buxi=="0"){
          value+="3";
        }
        if(!value){
          alert("入账类型必填!");
          isEnd=true;
          return ;
        }
        if(!code){
           alert("产品必选!");
           isEnd=true;
          return ;
        }
        console.log(value);
        $scope.productInfo[i].accountType=value;
      });
    if(isEnd){
      return ;
    }
    //删除产品名字
    angular.forEach($scope.productInfo,function(o,i){
        delete $scope.productInfo[i].productFullName;
    });
    $scope.accountVoucher.productInfo=angular.toJson($scope.productInfo);

    if($scope.id){//编辑
       delete $scope.accountVoucher.fpAccountVoucherProductList;
       fpAccountVoucherService.updateFpAccountVoucher($scope.accountVoucher).then(function(json){
         if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("编辑成功!!");
        }
        $route.reload();
        console.log(json);
      });
    }else{
       fpAccountVoucherService.addFpAccountVoucher($scope.accountVoucher).then(function(json){
         if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("新增成功!!");
        }
         $route.reload();
        console.log(json);
      });
    }
  }
  //新增空对象
  $scope.addItem = function(){
    $scope.productInfo.push({});
    $scope.showFullName($scope.productInfo.length-1);
  }
  //删除对象
  $scope.deleteItem = function(v){
    $scope.productInfo.splice(v,1);
  }

  $scope.changeMoney = function(){
    $scope.accountVoucher.allMoney=0;
    angular.forEach($scope.productInfo,function(o,i){
        var accountMoney=$scope.productInfo[i].accountMoney;
        if(accountMoney){
          $scope.accountVoucher.allMoney+=parseFloat(accountMoney);
        }
      });
  }

   $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.accountVoucher.accountVoucherUrl = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });
}]);
faApp.controller('HongbaoListCtrl',['$scope','hongbaoService','$location','$controller','$routeParams','$filter','exportService',function($scope,hongbaoService,$location,$controller,$routeParams,$filter,exportService) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.config = {
    "pageSize" : 200,
    "pageNo" : 1,
  };
  $scope.$watch('config',function(){
    hongbaoService.hongbaoList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
    });
  },true);


  $scope.export = function(){
    exportService.exportCSV($scope.config,"HONGBAO_LIST_EXPORT");
  };
}]);

faApp.controller('HongbaoDetailCtrl',['$scope','hongbaoService','$location','$controller','$routeParams','$filter',function($scope,hongbaoService,$location,$controller,$routeParams,$filter) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.config={fpGroupId:$routeParams.fpGroupId};
  $scope.listGroup={};
  $scope.listMember={};
  hongbaoService.hongbaoDetail($scope.config).then(function(json){
    $scope.listGroup=json.listGroup[0];
    $scope.listMember=json.listMember;
  });
  $scope.changeGroup=function(){
    
  hongbaoService.hongbaoJihuo($scope.config).then(function(json){
    if(json.statusCode==4009){
      alert("认证人数不足");
      return ;
    }else if (json.statusCode){
      alert("出错了:" + json.statusCode);
    }else{
      alert("激活成功");
    }
  });
  }


}]);

faApp.controller('IndexCtrl',['$scope','userService','$location','$controller','$rootScope','$timeout',function($scope,userService,$location,$controller,$rootScope,$timeout) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.nav = {"module":"product"};

  $scope.changeNavModule = function(v){
    $scope.nav.module = v;
  }; 
  $scope.checkLoginStatus();

  $timeout(function(){
    $scope.changeNavModule($("#J_tmenu li:first").attr("who"));
  },300);

}]); 

faApp.controller('IndexPanelCtrl',['$scope','userService','$location','$controller','$rootScope','operationService','$filter',function($scope,userService,$location,$controller,$rootScope,operationService,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.openPage = function(url,title,id){
    var data = {url:url,id:id,title:title};
    $scope.$emit("pageopen",data);
  }; 

  if ($scope.hasAuth("btn","OPERATION_STAT_COUNT")){
    var t = (new Date()).getTime();
    operationService.statCount({countDateBeginStr:$filter('date')(t - 86400000 * 7,'yyyy-MM-dd'),countDateEndStr:$filter('date')(t - 86400000,'yyyy-MM-dd')}).then(function(json){
      $scope.statData = json;  
    });
  }
}]);
faApp.controller('IndexEverydayCtrl',['$scope','userService','$location','$controller','$rootScope','operationService','$filter','ajaxService',function($scope,userService,$location,$controller,$rootScope,operationService,$filter,ajaxService) {
  $controller('BaseCtrl', {$scope: $scope});
  console.info('IndexEverydayCtrl');
  //我的业绩,团队业绩
  operationService.queryOrderOwnerUserCountAmount().then(function(json){
    console.info('我的业绩,团队业绩');
    console.log(json);
    $scope.resultstData = json;
  });
  //用户访问详情
  operationService.queryVistDetail().then(function(json){
    console.info('用户访问详情');
    console.log(json);
    $scope.visData = json;
  });
  //待办事项列表
  function getlistFaRevisitTask(){
    operationService.listFaRevisitTask({
      faRevisitType:'2'
    }).then(function(json){
      console.info('待办事项列表');
      console.log(json);
      $scope.taskData = json.list;
    });
  }
  getlistFaRevisitTask();
  //关注客户
  operationService.customerFocus().then(function(json){
    console.info('关注客户');
    console.log(json);
    $scope.cfData = json.list;
  });
  //标记已完成faRevisitTask/updateFaRevisitTask.shtml
  $scope.ckupTask = function(id){
    console.info('标记已完成');
    operationService.updateFaRevisitTask({
      id:id
    }).then(function(json){
      console.info('标记已完成');
      getlistFaRevisitTask();
    });
  };

}]);

faApp.controller('InfoManageFeedBackCtrl',['$scope','infoManageService','$location','$controller','$route',function($scope,infoManageService,$location,$controller,$route) {   
	
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.fbs = [];
  $scope.loading = true;
  $scope.showCon = false;

  $scope.$watch('config',function(){
    infoManageService.fbList($scope.config).then(function(json){
      $scope.fbs = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  
 $scope.showDiv = function(id){
    angular.forEach($scope.fbs,function(o){
      if(o.id==id){
        // $scope.showContent=o.fpContents;
        // $scope.showContent=o.fpContents.replace("＜","<").replace("＞",">");
        var c = o.fpContents.replace("＜","<").replace("＞",">");
        $("#showContent").html(c);
        $scope.showCon=true;
      }
    });
  };  
}]);

faApp.controller('InfoManageBankCardCtrl',['$scope','infoManageService','$location','$controller','$route',function($scope,infoManageService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope});  

  $scope.bcs = [];
  $scope.loading = true;

  $scope.search = function(){
    $scope.config = $scope.searchMap;
  }

  $scope.$watch('config',function(){
    infoManageService.bcList($scope.config).then(function(json){
      $scope.bcs = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };  
}]);

faApp.controller('InfoManageWithdrawCtrl',['$scope','infoManageService','$location','$controller','$route',function($scope,infoManageService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.withdraws = [];
  $scope.loading = true;

  $scope.search = function(){
    $scope.config = $scope.searchMap;
  }

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.$watch('config',function(){
    if(!$scope.config.withdrawStatus){
      $scope.config.withdrawStatus = "";
    }
    $scope.config.pageSize = 20;
    infoManageService.withdrawList($scope.config).then(function(json){
      $scope.withdraws = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);
}]);

faApp.controller('InfoManageWithdrawDetailCtrl',['$scope','infoManageService','$location','$controller','$route','$routeParams',function($scope,infoManageService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.withdraw = {};
  $scope.id = $routeParams.id;
  $scope.canEdit = false;

  if($scope.id){
    infoManageService.withdrawDetail($scope.id).then(function(json){
      $scope.withdraw = json.dto;
      if($scope.withdraw.withdrawStatus && $scope.withdraw.withdrawStatus == '01'){
        $scope.canEdit = true;
      }
    });
  }

  $scope.save = function(){
    infoManageService.withdrawUpdate($scope.withdraw).then(function(json){
      if (json.statusCode){
          alert(json.statusCode);
        }else{
          $route.reload();
        }
    });
  }
}]);

faApp.controller('InfoManageWithPayRunningCtrl',['$scope','infoManageService','$location','$controller','$route','$routeParams',function($scope,infoManageService,$location,$controller,$route,$routeParams) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.config.pageSize = 10;
  $scope.$watch('config', function(json) {   
    infoManageService.payRunningList($scope.config).then(function(json){
      $scope.withdraws = json.list;
      $scope.pager = json.pager;
    });
  }, true);
}]);

faApp.controller('InfoManageWithDrawAskForCtrl',['$scope','infoManageService','$location','$controller','$route',function($scope,infoManageService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.withdraws = [];
  $scope.payMoneyCheck = false;
  $scope.transferAcoutsFail = false;
  $scope.failReson =  '';


  $scope.search = function(){
    $scope.config = $scope.searchMap;
  }

  $scope.config = {
    "pageSize" : 10,
    "pageNo" : 1
  };

  $scope.$watch('config',function(){
    infoManageService.askForList($scope.config).then(function(json){
      $scope.withdraws = json.result;
      $scope.pager = json.pager;
    });
  },true);

  $scope.showHide = function(v,index){
    $scope.param = {
      'id' : $scope.withdraws[index].id,
      'platSerialNo' : $scope.withdraws[index].platSerialNo
    };
    if(v == '1'){
      $scope.payMoneyCheck = true;
      $scope.listIndex = index || 0;

    }else{
      $scope.transferAcoutsFail = true;
    }
  }
  $scope.submit = function(stg) {
    if(stg){
      if( !$scope.failReson) {
        alert('请填写失败原因');
        return;
      }else{
        $scope.param.remark = $scope.failReson;
        console.log($scope.param);
        infoManageService.askForFail($scope.param).then(function(json) {
          if (json.statusCode) {
            alert('出错了' + json.statusCode)
          } else {
            $route.reload();
          }
        })
      }
    }else{
      console.log($scope.param);
      infoManageService.askForSuccess($scope.param).then(function(json) {
        if (json.statusCode) {
          alert('出错了' + json.statusCode)
        } else {
          $route.reload();
        }
      })
    }
  };
}]);

faApp.controller('InfoManageWithDrawAskForDetailCtrl',['$scope','$routeParams','infoManageService','$location','$controller','$route',function($scope,$routeParams,infoManageService,$location,$controller,$route) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  console.log($scope.id);
  infoManageService.askForDetail($scope.id).then(function(json){
    $scope.withdraws = json.payList;
  })
}]);
faApp.controller('LicaishiManagerUserListCtrl',['$scope','licaishiManagerService','$location','$controller','$route',function($scope,licaishiManagerService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.licaishiManagerUserList = [];
  $scope.loading = true;

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      licaishiManagerService.list($scope.config).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList = json.list;
          $scope.pager = json.page;
          $scope.loading = false;
        }
      });
    }
  },true);  

  $scope.config = {
    "pageSize" : 10000,
    "pageNo" : 1
  };
  $scope.licaishiManager={};
  $scope.huishouManagerLicaishiByUser = function(uid){
    if(uid != undefined){
      if(confirm("确认要回收所有理财师权限吗？")){
        $scope.licaishiManager.systemUserId=uid;
        licaishiManagerService.huishouManagerLicaishiByUser($scope.licaishiManager).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            alert("回收成功！");
          }
        });
      }
    }
  }
}]);

faApp.controller('LicaishiManagerUserAddCtrl',['$scope','licaishiManagerService','$location','$controller','$route',function($scope,licaishiManagerService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.userNotManager = {};
  $scope.notLicaishiManagerUserList = [];

  licaishiManagerService.notLicaishiManagerUserList().then(function(json){
    if (json.statusCode){
      alert("出错了:" + json.statusCode);
    }else{
      $scope.notLicaishiManagerUserList = json.list;
    }
  });

  $scope.save = function(){
    if (!$scope.form.$invalid){
      licaishiManagerService.licaishiManagerUserAdd($scope.userNotManager).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("添加成功！");
          $route.reload();
        }
      });
    }else{
      alert("请选择人员！");
    }
  }

}]);
faApp.controller('LinkListCtrl',['$scope','linkService','$location','$controller','$route',function($scope,linkService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.ads = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    linkService.linkList($scope.config).then(function(json){
      $scope.ads = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	};

	$scope.linkDelete = function(id){
    linkService.linkDelete({id:id}).then(function(json){
      $route.reload();    
    });
	}; 
}]);

faApp.controller('LinkAddCtrl',['$scope','linkService','$location','$controller','$timeout',function($scope,linkService,$location,$controller,$timeout) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.ad = {"advertSort":10};
  $scope.loading = true; 

	$scope.save = function(){
    if ($scope.form.$invalid){
      if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
      if ($scope.form.pic.$invalid)$scope.form.pic.$dirty = true;
      if ($scope.form.link.$invalid)$scope.form.link.$dirty = true;
      if ($scope.form.startTime.$invalid)$scope.form.startTime.$dirty = true;
      if ($scope.form.endTime.$invalid)$scope.form.endTime.$dirty = true;
      if ($scope.form.sort.$invalid)$scope.form.sort.$dirty = true;
    }else{
      if ($scope.ad.startTime){$scope.ad.startTime = $scope.ad.startTime + " 00:00:00";}
      if ($scope.ad.endTime){$scope.ad.endTime = $scope.ad.endTime + " 23:59:59";}

      linkService.linkAdd($scope.ad).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/link/list");
        }
      });
    }
  };
 
}]);

faApp.controller('LinkEditCtrl',['$scope','linkService','$location','$controller','$routeParams','$filter',function($scope,linkService,$location,$controller,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.ad = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;

  /*
  linkService.linkQuery($scope.id).then(function(json){
    $scope.ad = json.dto;
    if ($scope.ad.startTime){ $scope.ad.startTime = $filter("date")($scope.ad.startTime,"yyyy-MM-dd"); }
    if ($scope.ad.endTime){ $scope.ad.endTime = $filter("date")($scope.ad.endTime,"yyyy-MM-dd"); }
  });
  */

  linkService.linkList().then(function(json){
    angular.forEach(json.list || [],function(o){
      if (o.id == $scope.id){
        $scope.ad = o;
      }  
    });  
  });

	$scope.save = function(){
    if ($scope.form.$invalid){
      if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
      if ($scope.form.pic.$invalid)$scope.form.pic.$dirty = true;
      if ($scope.form.link.$invalid)$scope.form.link.$dirty = true;
      if ($scope.form.startTime.$invalid)$scope.form.startTime.$dirty = true;
      if ($scope.form.endTime.$invalid)$scope.form.endTime.$dirty = true;
      if ($scope.form.sort.$invalid)$scope.form.sort.$dirty = true;
    }else{
      if ($scope.ad.startTime){$scope.ad.startTime = $scope.ad.startTime + " 00:00:00";}
      if ($scope.ad.endTime){$scope.ad.endTime = $scope.ad.endTime + " 23:59:59";}

      delete $scope.ad.color;
      linkService.linkEdit($scope.ad).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/link/list");
        }
      });
    }
  };
 
}]);


faApp.controller('LoginCtrl',['$scope','loginService','$location','$controller','ajaxService','sessionService',function($scope,loginService,$location,$controller,ajaxService,sessionService) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.checkBrowserEnv();
   
	$scope.login = function(){

		$scope.form.loginName.$dirty = true;
		$scope.form.password.$dirty = true;

		if ($scope.form.$valid) {

			var promise = loginService.login($scope.user);

			promise.then(function(data) {
				if (data.statusCode) {
					if ("0001" == data.statusCode) {
						$scope.markFieldError($scope.form.password,"passerror");
            return;
					}
				} else {
					$scope.setLogined(data); 
          sessionService.setItem("user",angular.toJson($scope.loginStatus) || "");
          sessionService.setItem("user.access",data.access || "");
          if (data.access == "all"){
            sessionService.setItem("user.groups",data.access || "");
          }else{
            var groups = [];
            angular.forEach(data.groups || [],function(o){
              groups.push(o.groupId);
            });
            sessionService.setItem("user.groups",groups || "");
          }

          $location.path("/index");
				}
			}, function(data) {
				
			});
		}
	};
	$scope.upUserInfo = function(){
		$scope.form.oldPassword.$dirty = true;
		$scope.form.newPassword.$dirty = true;
		$scope.form.telePhone.$dirty = true;
		$scope.form.email.$dirty = true;

		if($scope.user.newPassword != $scope.user.oldPassword){
			alert('两次密码不一致');
			return
		}
		if ($scope.form.$valid) {
			$scope.user.password = $scope.user.newPassword;
			var promise = loginService.updateLoginInfo($scope.user);

			promise.then(function(data) {
				//从登陆看，走到这一步就算登陆成功了
				alert('修改密码成功');
				$location.path("/index");

			}, function(data) {

			});
		}
	}

}]);

faApp.controller('LogoutCtrl',['$scope','loginService','$location','$controller','ajaxService',function($scope,loginService,$location,$controller,ajaxService) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  loginService.logout().then(function(){
    $scope.logout();
    $location.path("/login");
  });
}]);

faApp.controller('M2bWinListCtrl',['$scope','m2bService','$location','$controller','$route',function($scope,m2bService,$location,$controller,$route) {   
	$controller('BaseListCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    m2bService.winList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.stop = function(id){
    adService.adStop({id:id,status:"02"}).then(function(json){
      $route.reload();    
    });
	}; 
}]);

faApp.controller('MediaRecommendListCtrl', ['$scope', '$location', '$controller', '$route', 'productService', 'mediaService', 'simuService', function($scope, $location, $controller, $route, productService, mediaService, simuService) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.list = [];
  $scope.loading = false;

  $scope.$watch('config', function() {
    mediaService.mediaRecommendList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.page;
    });
  }, true);
 
  $scope.config = {
    "pageSize": 20,
    "pageNo": 1
  };

  $scope.meida = {productType: '', productCode: '', productName: '', mediaSource: '', productList: {}};

  var tmpType = '';
  $scope.$watch('meida.productType', function() {
    if($scope.meida.productType && ($scope.meida.productType == '04')){
      alert('暂不支持此类型！');
      $scope.meida.productType = tmpType;
      return;
    }

    if($scope.meida.productType && (tmpType != $scope.meida.productType)){
      $scope.loading = true;
      tmpType = $scope.meida.productType;
      var param = {
        pageNo:1, 
        pageSize:1000,
        pTypeList:$scope.meida.productType, 
        pPublicStatus:'2'
      };
      // 根据类型查询对应的产品列表
      if($scope.meida.productType == '06'){
        // PE/VC
        productService.queryProductList(param).then(function(json){
          $scope.meida.productList = json.list;
          // 删除已经添加的！
          exclude();

          $scope.loading = false;
        });
      }else if($scope.meida.productType == '02' || $scope.meida.productType == '03'|| $scope.meida.productType == '07'){
        // 信托资管
        productService.productList(param).then(function(json){
          $scope.meida.productList = json.projectList;
          
          // 删除已经添加的！
          exclude();
          
          $scope.loading = false;
        });
      }else if($scope.meida.productType == '01'){
        // 阳光私募
        simuService.list(param).then(function(json){
          $scope.meida.productList = json.list;
          
          // 删除已经添加的！
          exclude();
          $scope.loading = false;
        });
      }
    }
  }, true);

  $scope.mediaAddRecommend = function(){
    if($scope.meida.productCode && $scope.meida.productType && $scope.meida.recommentType){
      var o = {
        productType: $scope.meida.productType,
        productCode: $scope.meida.productCode,
        recommentType : $scope.meida.recommentType

      };

      mediaService.mediaRecommendAdd(o).then(function(json){
        if(!json.statusCode){
          mediaService.mediaRecommendList($scope.config).then(function(json){
            $scope.list = json.list;
            $scope.pager = json.page;
            // 删除已经添加的！
            exclude();

            $scope.loading = false;
          });
        }else{
          if(json.statusCode == '2003'){
            alert('重复添加！');
          }else if(json.statusCode == '2009'){
            alert('产品不存在！');
          }else{
            alert('error' + json.statusCode);
          }
        }
      });
    }else{
      alert('请选择产品和类型！');
    }
  }

  $scope.delete = function(id) {
    if(confirm('确定删除吗！')){
      mediaService.mediaRecommendDelete({ id: id }).then(function(json) {
        if(!json.statusCode){
          alert('删除成功！');
          $route.reload();
        }else{
          alert('error：' + json.statusCode);
          $route.reload();
        }
      });
    }
  };

  function exclude() {
    var tmp = angular.copy($scope.meida.productList);
    var c = 0;
    var id = 0;
    angular.forEach(tmp, function(i, o) {
      id = i.pCode || i.id;
      angular.forEach($scope.list, function(j) {
        if (id == j.productCode) {
          $scope.meida.productList.splice((o - c), 1);
          c++;
          $scope.meida.productCode = '';
        }
      })
    });
  }

}]);

faApp.controller('MessageListCtrl', ['$scope','MessageService','exportService','$location','$controller','$route','$routeParams','$filter',
function($scope,MessageService,exportService,$location,$controller,$route,$routeParams,$filter) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.message = {};
  $scope.list = [];
 
  $scope.addOrEdit = "编辑";

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      MessageService.messageList($scope.config).then(function(json){
        $scope.list = json.list;
        //$scope.pager = json.pager;
        $scope.loading = false;
      }); 
    }
  },true);

  $scope.isEdit = {};
  $scope.messageContent = {};
  $scope.messageType = {};
  $scope.messageRemark = {};
  // 显示编辑框
  $scope.toUpdate = function(id){
    $($scope.list).each(function(i){
      $scope.isEdit[$scope.list[i]['id']] = false;
    });

    $scope.isEdit[id] = true;
  };
  // 保存编辑内容
  $scope.updateContent = function(id){
    //if($scope.messageContent[id] != undefined && $scope.messageContent[id].length > 0){
    if($scope.messageContent[id] != undefined && $scope.messageContent[id].length > 500){
      alert("内容最多500个字符！");
      return;
    }
    $scope.message.id = id;
    $scope.message.smsType = $scope.messageType[id];
    $scope.message.smsContent = $scope.messageContent[id];
    $scope.message.smsRemark = $scope.messageRemark[id];

    MessageService.messageEdit($scope.message).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改成功！");
        $route.reload();
      }
    });
    // }else{
    //   alert("内容不能为空！");
    //   return;
    // }
    //$scope.isEdit[id] = false;
  };
}
]);
faApp.controller('MillionListCtrl',['$scope','millionService','productService','$location','$controller','$route',function($scope,millionService,productService,$location,$controller,$route) {   
  $scope.ctrlName = "MillionListCtrl";
	$controller('BaseListCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      millionService.list($scope.config).then(function(json){
        $scope.list = json.list;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  },true);
 
  
  $scope.products = [];
  $scope.searchProduct2 = function(){
    console.log($scope.productKw);
    if ($scope.productKw){
      $scope.showSearchCombox = true;
      $scope.loaded = false;
      productService.productList({pPublicStatus:2,pName:$scope.productKw}).then(function(json){
        $scope.products = json.projectList;
        $scope.pager = json.projectDTO;
        $scope.loaded = true;
      });
    }else{
      $scope.searchMap.pId = "";
      $scope.searchMap.productKw = "";
      $scope.showSearchCombox = false;
    }
  };
  
  $scope.selectProduct = function(id,name){
    $scope.searchMap.pId = id;
    $scope.productKw = name;
    $scope.showSearchCombox = false;
  };
  
  $scope.remove = function(id){
    millionService.remove({id:id}).then(function(json){
      $route.reload();
    });
  };
}]);

faApp.controller('MillionAddCtrl',['$scope','millionService','productService','$location','$controller','$timeout', 'activityService','simuService','$route', function($scope,millionService,productService,$location,$controller,$timeout, activityService,simuService,$route) {
	$controller('MillionListCtrl', {$scope: $scope}); 

  $scope.activityCode = $location.search().activityCode || '';

  $scope.item = {};
  $scope.loading = true;
  $scope.activityList = {};
  $scope.activityListAll = {};

  // 新增，从后台查询所有活动内容
  activityService.activityNameList({isExpired: '01', isStatus: '01'}).then(function(json){
    $scope.activityList = json.list;

    $scope.item.activitiesCode = $scope.activityCode;
  });

  activityService.activityNameList().then(function(json){
    $scope.activityListAll = json.list;
  });

	$scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else{
      if ($scope.item.endTimeStr < $scope.item.beginTimeStr){
        alert("结束时间应该晚于开始时间");
        return;
      }
      if ($scope.item.beginTimeStr){$scope.item.beginTime = $scope.item.beginTimeStr + " 00:00:00";}
      if ($scope.item.endTimeStr){$scope.item.endTime = $scope.item.endTimeStr + " 23:59:59";}

      millionService.add($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");

          $route.reload();
          // $location.path("/million/list");
        }
      });
    }
  };
  
  
  $scope.products = [];
  $scope.searchProduct = function(){
    $scope.showSearchCombox = true;
    $scope.loaded = false;
    // productService.productList({pPublicStatus:2,pName:$scope.productKw,pSaleStatus:'03'}).then(function(json){
    productService.productList({pPublicStatus:2,pName:$scope.productKw}).then(function(json){
      $scope.products = json.projectList;
      $scope.pager = json.projectDTO;
      $scope.loaded = true;
    });
  };
  
  $scope.selectProduct = function(id){
    $scope.item.pId = id;
    
    angular.forEach($scope.products,function(o){
      if (o.id == id){
        
        millionService.list({pId:id,activitiesCode:$scope.item.activitiesCode}).then(function(json){
          if (json && json.list && json.list.length > 0){
            alert("此产品已经在参与活动了");
            $scope.productKw = "";
            return;
          }else{
            $scope.product = o;
            $scope.productKw = o.pName;
            
            productService.productQuery($scope.product.id).then(function(json){
              $scope.product = json.project;
              $scope.loading = false; 
              $scope.projectRabateList = json.projectRabateList;
              $scope.minRebate = 99999999;
              if ($scope.projectRabateList && $scope.projectRabateList.length > 0){
                angular.forEach($scope.projectRabateList,function(o){
                  if (o.pRabateProfit < $scope.minRebate){
                    $scope.minRebate = o.pRabateProfit;
                  }
                });
              }
            });
          }
        });
          
        $scope.showSearchCombox = false;
      }
    });
  };
  
  $scope.selectAct = function(){
    $scope.item.pId && $scope.selectProduct($scope.item.pId);
  };
 
  $scope.clickedSomewhereElse = function(){
    $scope.showSearchCombox = false;
  };

  $scope.activityProduct = {pType: '', pId: '', productName: '', activitiesCode: '', productList: {}};

  $scope.changeActivity = function(){
    $scope.activityProduct.pType = '';
    $scope.activityProduct.productList = {};
  }

  var tmpType = '';
  $scope.$watch('activityProduct.pType', function() {
    if($scope.activityProduct.pType && ($scope.activityProduct.pType == '04')){
      alert('暂不支持此类型！');
      $scope.activityProduct.pType = tmpType;
      tmpType = '';
      return;
    }

    if($scope.activityProduct.pType && (tmpType != $scope.activityProduct.pType)){
      $scope.loading = true;
      tmpType = $scope.activityProduct.pType;
      var param = {
        pageNo:1, 
        pageSize:1000,
        pTypeList: $scope.activityProduct.pType, 
        pPublicStatus:'2',
        activitiesCode: $scope.activityProduct.activitiesCode, 
      };

      // 根据类型查询对应的产品列表
      if($scope.activityProduct.pType == '06'){
        // PE/VC
        productService.queryProductList(param).then(function(json){
          $scope.activityProduct.productList = json.list;

          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }else if($scope.activityProduct.pType == '02' || $scope.activityProduct.pType == '03'){
        // 信托资管
        productService.productList(param).then(function(json){
          $scope.activityProduct.productList = json.projectList;
          
          // 删除已经添加的！
          // exclude();
          
          $scope.loading = false;
        });
      }else if($scope.activityProduct.pType == '01'){
        // 阳光私募
        simuService.list(param).then(function(json){
          $scope.activityProduct.productList = json.list;
          
          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }
    }
  }, true);

  $scope.addActivityProduct = function(){
    if ($scope.form.$invalid){
      alert('请填写完整！');
      return;
    }

    if(!$scope.activityProduct.activitiesCode){
      alert('请选择活动！');
    }else if(!$scope.activityProduct.pType){
      alert('请选择产品类型！');
    }else if(!$scope.activityProduct.pId){
      alert("请选择产品！");
    }else{
      if ($scope.activityProduct.endTimeStr < $scope.activityProduct.beginTimeStr){
        alert("结束时间应该晚于开始时间");
        return;
      }
      if ($scope.activityProduct.beginTimeStr){$scope.activityProduct.beginTime = $scope.activityProduct.beginTimeStr + " 00:00:00";}
      if ($scope.activityProduct.endTimeStr){$scope.activityProduct.endTime = $scope.activityProduct.endTimeStr + " 23:59:59";}
      


      millionService.list({pId:$scope.activityProduct.pId, activitiesCode:$scope.activityProduct.activitiesCode}).then(function(json){
        if (json && json.list && json.list.length > 0){
          alert("此产品已经在参与活动了");
          return;
        }else{
          $scope.activityProduct.productList = {};

          millionService.add($scope.activityProduct).then(function(json){
            if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.activityProduct = {pType: '', pId: '', productName: '', activitiesCode: '', productList: {}};

              $scope.alertNextPage("操作成功");

              $route.reload();
              // $location.path("/million/list");
            }
          });

        }
      });

    }
  }

}]);

faApp.controller('MillionEditCtrl',['$scope','millionService','productService','$location','$controller','$routeParams','$filter','activityService','$route',function($scope,millionService,productService,$location,$controller,$routeParams,$filter,activityService,$route) {
	$controller('MillionListCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;

  $scope.activityCode = $location.search().activityCode || '';

  $scope.activityList = {};

  // 新增，从后台查询所有活动内容
  activityService.activityNameList().then(function(json){
    $scope.activityList = json.list;

    $scope.item.activitiesCode = $scope.activityCode;
  });

  millionService.list({id:$scope.id}).then(function(json){
    $scope.loading = false; 
    
    if (json.list && json.list.length > 0){
      $scope.item = json.list[0]['activitiesMollionsWealth'];
      $scope.product = json.list[0]['product'];
      if ($scope.item.beginTime){ $scope.item.beginTimeStr = $filter("date")($scope.item.beginTime,"yyyy-MM-dd"); }
      if ($scope.item.endTime){ $scope.item.endTimeStr = $filter("date")($scope.item.endTime,"yyyy-MM-dd"); }
      
      productService.productProfitList($scope.product.id).then(function(json){
        $scope.loading = false; 
        $scope.projectRabateList = json.projectRabateList;
        $scope.minRebate = 99999999;
        if ($scope.projectRabateList && $scope.projectRabateList.length > 0){
          angular.forEach($scope.projectRabateList,function(o){
            if (o.pRabateProfit < $scope.minRebate){
              $scope.minRebate = o.pRabateProfit;
            }
          });
        }
      });
    }

  });

	$scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else{
      if ($scope.item.endTimeStr < $scope.item.beginTimeStr){
        alert("结束时间应该晚于开始时间");
        return;
      }
      if ($scope.item.beginTimeStr){$scope.item.beginTime = $scope.item.beginTimeStr + " 00:00:00";}
      if ($scope.item.endTimeStr){$scope.item.endTime = $scope.item.endTimeStr + " 23:59:59";}

      millionService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");

          $route.reload();
          // $location.path("/million/list");
        }
      });
    }
  };
  
  $scope.products = [];
  $scope.searchProduct = function(){
    $scope.showSearchCombox = true;
    $scope.loaded = false;
    // productService.productList({pPublicStatus:2,pName:$scope.productKw,pSaleStatus:'03'}).then(function(json){
    productService.productList({pPublicStatus:2,pName:$scope.productKw}).then(function(json){
      $scope.products = json.projectList;
      $scope.pager = json.projectDTO;
      $scope.loaded = true;
    });
  };
  
  $scope.selectProduct = function(id){
    $scope.item.pId = id;
    
    angular.forEach($scope.products,function(o){
      if (o.id == id){
        
        millionService.list({pId:id}).then(function(json){
          if (json && json.list && json.list.length > 0){
            alert("此产品已经在参与活动了");
            $scope.productKw = "";
            return;
          }else{
            $scope.product = o;
            $scope.productKw = o.pName;
          }
        });
      }
    });
    $scope.showSearchCombox = false;
  };

  $scope.clickedSomewhereElse = function(){
    $scope.showSearchCombox = false;
  }; 

  $scope.activityProduct = {pType: '', pId: '', productName: '', activitiesCode: '', productList: {}};

  var tmpType = '';
  $scope.$watch('activityProduct.pType', function() {
    if($scope.activityProduct.pType && ($scope.activityProduct.pType == '04')){
      alert('暂不支持此类型！');
      $scope.activityProduct.pType = tmpType;
      return;
    }

    if($scope.activityProduct.pType && (tmpType != $scope.activityProduct.pType)){
      $scope.loading = true;
      tmpType = $scope.activityProduct.pType;
      var param = {
        pageNo:1, 
        pageSize:1000,
        pTypeList:$scope.activityProduct.pType, 
        pPublicStatus:'2'
      };
      // 根据类型查询对应的产品列表
      if($scope.activityProduct.pType == '06'){
        // PE/VC
        productService.queryProductList(param).then(function(json){
          $scope.activityProduct.productList = json.list;

          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }else if($scope.activityProduct.pType == '02' || $scope.activityProduct.pType == '03'){
        // 信托资管
        productService.productList(param).then(function(json){
          $scope.activityProduct.productList = json.projectList;
          
          // 删除已经添加的！
          // exclude();
          
          $scope.loading = false;
        });
      }else if($scope.activityProduct.pType == '01'){
        // 阳光私募
        simuService.list(param).then(function(json){
          $scope.activityProduct.productList = json.list;
          
          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }
    }
  }, true);

  $scope.addActivityProduct = function(){
    if ($scope.form.$invalid){
      alert('请填写完整！');
      return;
    }

    if(!$scope.activityProduct.activitiesCode){
      alert('请选择活动！');
    }else if(!$scope.activityProduct.pType){
      alert('请选择产品类型！');
    }else if(!$scope.activityProduct.pId){
      alert("请选择产品！");
    }else{
      if ($scope.activityProduct.endTimeStr < $scope.activityProduct.beginTimeStr){
        alert("结束时间应该晚于开始时间");
        return;
      }
      if ($scope.activityProduct.beginTimeStr){$scope.activityProduct.beginTime = $scope.activityProduct.beginTimeStr + " 00:00:00";}
      if ($scope.activityProduct.endTimeStr){$scope.activityProduct.endTime = $scope.activityProduct.endTimeStr + " 23:59:59";}
      
      $scope.activityProduct.productList = {};

      millionService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");

          $route.reload();
          // $location.path("/million/list");
        }
      });

    }
  }

}]);


//渠道管理员查询所有订单   
//该方法2017年7月26日 改造 目的：合并页面和ctrl
faApp.controller('NewOrderListGZCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {

  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.role=$routeParams.role;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }

  $scope.statusMap = {};

  $scope.target="";
  var hasPage = "";
  if($scope.role=='qd'){//渠道
    hasPage = 'hasPageNewOrderQDM';
    $scope.target="0";
  }else if($scope.role=='qdm'){//qdm对应渠道管理员
    hasPage = 'hasPageNewOrderQDA';
     $scope.target="1";
  }else if($scope.role=='cp'){//cp代表产品经理
    hasPage = 'hasPageNewOrderCPM';
    $scope.target="";
  }else if($scope.role=='cpm'){//cp代表产品管理员
     hasPage = 'hasPageNewOrderCPA';
     $scope.target="";
  }else if($scope.role=='cwa'){
    hasPage = 'hasPageNewOrderCWA';
    $scope.target="";
  }else if($scope.role=='cwam'){
    hasPage = 'hasPageNewOrderCWGLY';
    $scope.target="";
  }

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      if($scope.role=='qdm'){
        //渠道管理查询所有订单
        newOrderService.qdalist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='qd'){
        //渠道查询单个订单
        newOrderService.qdmlist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cp'){
        newOrderService.cpmlist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cpm'){
        newOrderService.cpalist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }else if($scope.role=='cwa'){//查询全部的
       newOrderService.cwalist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.statusMap=json.statusMap;
        $scope.pager = json.page;
        $scope.loading = false;
      });
      }else if($scope.role=='cwam'){//财务管理  查询自己的
        newOrderService.cwaglylist($scope.config).then(function(json) {
          $scope.list = json.orderList;
          $scope.statusMap=json.statusMap;
          $scope.pager = json.page;
          $scope.loading = false;
        });
      }
      
    }
  }, true);
  //role 角色   m 列表条件
  $scope.ctrType=$scope.role.substr(0, 2);
 /* if($scope.role=='cwa'||$scope.role=='cwam'){
    if($scope.m=='01'||$scope.m=='05'){
       $scope.ctrType += "_wwcdd";//未完成订单
    }else if($scope.m=='02'||$scope.m=='06'){
       $scope.ctrType += "_ywcdd";//已完成
    }
  }*/
   if($scope.m=='01'||$scope.m=='05'){
   // $scope.ctrType += "_wwcdd";//未完成
    $scope.ctrType += "_wddd";//全部订单
  }
 /*  列表合并  只有一个m值
  else if($scope.m=='02'||$scope.m=='06'){
    $scope.ctrType += "_ywcdd";//已完成
  }else if($scope.m=='04'||$scope.m=='08'){
    $scope.ctrType = "ddsb";//失败
  }*/
  else if($scope.m=='03'||$scope.m=='07'){
    $scope.ctrType += "_hdfydd";//后端
  }
  else if($scope.m=='09'){
    $scope.ctrType += "_dshdd";//待审核
  }

  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.ctrType
  };

  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07",
    "target": $scope.target
  };

  newOrderService.queryOrderList($scope.fit).then(function(json) {
    $scope.orderList = json.list || [];
  });

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;
  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.orderStatusSelected="all";
  $scope.changeStatus = function(v) {
    $scope.config['orderSonCtrType'] = v;
    $scope.orderStatusSelected=v;
    $scope.search();
  };

  $scope.search = function(reload) {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }

    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);
      var appendStr="?";
      if(address.indexOf("?")>-1){
        appendStr="&";
      }
      var url = address +appendStr +'m='+$scope.m+'&role='+$scope.role+ '&id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType,address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }
      var appendStr="?";
      if(address.indexOf("?")>-1){
        appendStr="&";
      }
      var url = address + appendStr +'k=' +$scope.m  +'&role='+$scope.role + '&pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }
    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  //分配和回收处理
  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.managerOrder = {};

  $scope.fenpeiOrHuishou = function(t) {
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "02";
    $scope.managerOrder.faids = $scope.faids;

    if (t == "1") {
      if ($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != "") {
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            if (json.statusCode == '4001') {
              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if (json.mess != undefined) {
                angular.forEach(json.mess, function(o) {
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if (confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")) {
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
                  if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                  } else {
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            } else {
              alert("出错了:" + json.statusCode);
            }
          } else {
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        }, function(res) {
          alert('网络状态不稳定或超时！');
        });

      } else {
        alert("请选择订单跟进人！");
      }
    } else if (t == '0') {

      var tmpid = "";
      angular.forEach($scope.omu.split(","), function(o, i) {
        if (i == 0) {
          tmpid = o;
        } else {
          if (o != undefined && o != "" && o != tmpid) {
            tmpid = "99";
          }
        }
      });

      if (tmpid != undefined && tmpid != "99") {
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      } else {
        if (confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")) {
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  }

  $scope.getLastSearchConfig();
  $scope.search(true);
}]);

faApp.controller('NewOrderBaseCtrl',['$scope', 'newOrderService','$location','$controller','$routeParams','$filter','sessionService',function($scope,newOrderService,$location,$controller,$routeParams,$filter,sessionService) {
  $scope.id = $routeParams.id;
  $scope.m=$routeParams.m;
  $scope.role=$routeParams.role;
  $scope.tabUrl = {};
  $scope.item ={};
  $scope.tabUrlMap = {};
  $scope.lastProductTab = sessionService.getItem('lastProductTab') || 'orderUrl'; 
  $scope.paramTabUrl=$routeParams.paramTabUrl;
  if($scope.paramTabUrl){
    $scope.lastProductTab=$scope.paramTabUrl;
  }
  newOrderService.queryOrderDetail({
    'orderId': $scope.id,
    'role':$routeParams.role
  }).then(function(json) {
    $scope.item = json.orderDetail || {};
    $scope.loading = false; 
    var oType="";
    if($scope.item.oPType=='02'){
        oType="01";
      }else if($scope.item.oPType=='03'){
        oType="02";
      }
    //需要等待获取订单信息  初始化
    $scope.tabUrlMap = {
      orderUrl : "#/neworder/neworder0815/view?hdjy="+$routeParams.hdjy+"&m="+$scope.m+'&role='+$scope.role+ '&id=' + $scope.id + '&pType=' + $scope.item.oPType,
      dataUrl : "#/order/phoUpload?head=no&k=" +$scope.m  +'&role='+$scope.role + '&pId=' + $scope.item.oProjectId + '&oId=' + $scope.id + '&pType=' + $scope.item.oPType + '&oType=' + oType,
      cpDataUrl : "#/productOrderData/edit?head=no&k=" +$scope.m  +'&role='+$scope.role + '&pId=' + $scope.item.oProjectId + '&oId=' + $scope.id + '&pType=' + $scope.item.oPType + '&oType=' + oType,
      contractUrl : "#/neworder/neworder0815/contract/view?m="+$scope.m+'&role='+$scope.role+ '&id=' + $scope.id,
    };
    //默认选择
    $scope.changeTab('orderUrl');

  });

  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };

  angular.element(document).ready(function(){
     console.log($(window).height());
     //设置全部高度-30
    if ($(window).height() > 300) {
      console.info("执行")
        // $scope.iframeHeight = $(window).height()-30;
        $(".orderIframe").height($(window).height()-130)
        }

  });

}]);

faApp.controller('OrderContractCtrl',['$scope', 'newOrderService','$location','$controller','$route','$routeParams','$filter','sessionService',function($scope,newOrderService,$location,$controller,$route,$routeParams,$filter,sessionService) {   
    $controller('BaseCtrl', {$scope: $scope}); 
    $scope.id = $routeParams.id;
    $scope.m=$routeParams.m;
    $scope.role=$routeParams.role;
    $scope.item ={};
    newOrderService.queryOrderContract({
      'orderId': $scope.id
    }).then(function(json) {
      $scope.item = json.dto || {};
      console.log($scope.item);
      $scope.loading = false;
    });
    $scope.orderItem = {};

    $scope.booleanInsert=false;

     newOrderService.queryOrderDetail({
      'orderId': $scope.id
    }).then(function(json) {
      $scope.orderItem = json.orderDetail || {};
      console.log($scope.orderItem);
      var oStatus=$scope.orderItem.oStatus;
      console.log(oStatus);
      $scope.booleanInsert = (oStatus!='999'&&oStatus!='888'&&oStatus!='140'&&oStatus>='130');
      
      $scope.loading = false;
    });

    $scope.save = function(v){
      //必须参数判定，订单id设置
      if($scope.form.$invalid){
        alert("请填写完整表单");
        return ;
      }
      if(v=='05'){
        //合同封面不能为空
        if($scope.item.contractCover==''||$scope.item.contractCover==undefined){
          alert("请填写完整表单");
          return ;
        }
        //合同回收 判断  寄出合同编码和回收合同编码是否一致
        if($scope.item.contractBackCode!=$scope.item.contractCode){
          alert("寄出合同编码和回收合同编码不一致");
          return ;
        }
      }
       $scope.item.contractStatus=v;
      //判断如果新增则需要判断是否为预约成功
      if(!$scope.item.id){
        //目前订单状态是否可以支持申请合同
        if(!$scope.booleanInsert){
          alert("订单预约成功后才可以申请合同");
          return ;
          
        }
      }
      $scope.item.orderId=$scope.orderItem.orderId;
      newOrderService.orderContractUpdate($scope.item).then(function(json) {
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功！");
          $route.reload();
        }
      });

    }

   $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.item.contractCover = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);
//新订单流程详情页   不改动原有contrl
faApp.controller('NewOrderViewCtrl', ['$scope', 'newOrderService', '$location', '$controller', '$route', '$routeParams', '$filter', function($scope, newOrderService, $location, $controller, $route, $routeParams, $filter) {
  $scope.ctrlName = "NewOrderViewCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });
  $scope.hdjy=$routeParams.hdjy;//是否显示后端结佣申请
  $scope.isShowVisitLayer = false;
  $scope.isShowVisitLayer2 = false;
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {
    'id': $scope.id
  };
  $scope.pType = $routeParams.pType;
  $scope.s = $routeParams.s;
  $scope.m=$routeParams.m;
  $scope.role=$routeParams.role;
  $scope.bankCardList = {};

  $scope.showEdit=false;
  $scope.clickCount=0;

  newOrderService.queryOrderDetail({
    'orderId': $scope.id,
    'role' : $scope.role
  }).then(function(json) {
    $scope.item = json.orderDetail || {};
    $scope.bankCardList = json.bankCardList;
    $scope.backList = json.backList;
    $scope.item.wanAmount = $scope.item.oAmount/10000;
    $scope.loading = false;

  });


  //审核
  $scope.isInvestigate = function(id,status) {
     var oStatus="", auditFlag="";
     var reson="审核通过";
      if(status=='yes'){
        oStatus='130';
        reson="";
        auditFlag="chengjiaojiaAudit";
      }else{
        oStatus='140';
        reson="审核未通过";
      }
      newOrderService.updateOrderStatusAndOther({
        'id': id,
        'oStatus': oStatus,
        'oCancelReason': reson,
        'auditFlag':auditFlag
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
    //渠道设置结佣打款账号
  $scope.setCommissionInformation = function(v){
    $scope.item.bankName=v.bankName;
    $scope.item.cardNumber=v.cardNumber;
    $scope.item.userName=v.userName;
  } 

  //累积增加
  $scope.clicknum = function(v){
    if(v==1){
      $scope.clickCount=1;
    }else if($scope.clickCount==3){
      $scope.showEdit=true;
    }else if(v==2&&$scope.clickCount>=1){
      $scope.clickCount+=1;
    }
    console.log($scope.clickCount);
  }
  
  //预约成功
  $scope.applySuccess = function(v) {

    if(v){
      $scope.oCName = $scope.item.oCName;
      $scope.oAmount = $scope.item.wanAmount*10000;
      $scope.uInfo = {
        'id': $scope.id,
        'oCName':$scope.oCName,
        'oAmount':$scope.oAmount,
        'oStatus': '110',
        'updateInfo':true
      };
      newOrderService.updateOrderStatusAndOther($scope.uInfo).then(function(json) {
        if (json.statusCode) {
          switch (json.statusCode){
            case '2302':alert('订单购买金额小于起购金额')
              break;
            case '2304':alert('累进金额错误')
              break;
            case  '2303':alert('订单购买金额大于预售金额')
              break;
          };
        } else {
          $route.reload();
        }
      });
      return;
    }
    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;


    $scope.oSellingPrice = $scope.item.oSellingPrice;
    $scope.oBackSellingPrice = $scope.item.oBackSellingPrice;

    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;
    $scope.oTransactionPrice = $scope.item.oTransactionPrice;
    $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
    if ($scope.item.oBackCorePrice == undefined) {
      $scope.oBackTransactionRebate = $scope.item.oTransactionRebate;
    } else {
      $scope.oBackTransactionRebate = $scope.item.oBackTransactionPrice * $scope.item.oAmount / 100;
    }

    $scope.oKnotType = $scope.item.oKnotType
    $scope.yuyuesuccess = {
      'id': $scope.id,
      'oCName':$scope.oCName,
      'oAmount':$scope.oAmount,
      'oStatus': '130',
      'oTransactionPrice': $scope.oTransactionPrice,
      'oBackTransactionPrice': $scope.oBackTransactionPrice,
      'oTransactionRebate': $scope.oTransactionRebate,
      'oBackTransactionRebate': $scope.oBackTransactionRebate,
      'oKnotType': $scope.oKnotType,
    };
    if (!$scope.form.$invalid) {
      //有没有后端，没有就不让输入，有就输入
      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $route.reload();
          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，待产品经理审核");
          $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        } else if($scope.oBackTransactionPrice > $scope.oBackSellingPrice){
            alert("后端成交价大于后端核心价，待产品经理审核");
            $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        }
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
              if (json.statusCode) {
                alert("出错了:" + json.statusCode);
              } else {
                $route.reload();
              }
        });
      }
    }
  };
  //已寄出有效合同
  $scope.sendContract = function() {

    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '210'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };


  //确认已签约打款
  $scope.process = function(status) {
    if ($scope.form.$invalid) {
      alert("请选择结佣账号,提醒理财师绑卡!");
      return ;
    }
    if(!($scope.item.userName&&$scope.item.cardNumber&&$scope.item.bankName)){
      alert("请选择结佣账号,提醒理财师绑卡!");
      return ;
    }
    $scope.qryqydangkang = {
      'id': $scope.id,
      'oStatus': '220',
      'userName':$scope.item.userName,
      'cardNumber':$scope.item.cardNumber,
      'bankName':$scope.item.bankName 
    };
    newOrderService.updateOrderStatusAndOther($scope.qryqydangkang).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2006') {
          alert("还有资料未审核通过不能返佣!!!");
        } else {
          alert("出错了:" + json.statusCode);
        }
      } else {
        $route.reload();
      }
    });
  };


  //确认打款
  $scope.comfirmPay = function() {
    if(!$scope.item.flagBaoxiao){
      alert("请分类包销分销!!");
      return ;
    }

    $scope.qrdangkang = {
        'id': $scope.id,
        'oStatus': '240',
        'flagBaoxiao':  $scope.item.flagBaoxiao,
    };
    newOrderService.updateOrderStatusAndOther($scope.qrdangkang).then(function(json) {
      if (json.statusCode) {
         if(json.statusCode=='2305'){
          alert("超募，请查看是否超出本期募集规模!!!");
        }else{
           alert("出错了:" + json.statusCode);
        }
       
      } else {
        $route.reload();
      }
    });
  };

  //佣金到账
  $scope.frontRabite = function(v) {
    $scope.userName = $scope.item.userName;
    $scope.cardNumber = $scope.item.cardNumber;
    $scope.bankName = $scope.item.bankName;
    $scope.costAmount = $scope.item.costAmount;
    $scope.activityFunds = $scope.item.activityFunds;
    $scope.otherFunds = $scope.item.otherFunds;
    $scope.remark = $scope.item.remark;
    $scope.otherRemark = $scope.item.otherRemark;
    $scope.activityRemark = $scope.item.activityRemark;
    var stat="";
    var backStat="";
    if(v=='quanduan'){//前端佣金到帐
      stat='310';
    }else if(v=='houduan'){//后端佣金到帐
      backStat='311';
    }

      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.qdyjdaozhang = {
      'id': $scope.id,
      'oStatus': stat,
      'oBackStatus': backStat,
      'userName': $scope.userName,
      'bankName': $scope.bankName,
      'cardNumber': $scope.cardNumber,
      'costAmount': $scope.costAmount,
      'activityFunds': $scope.activityFunds,
      'otherFunds': $scope.otherFunds,
      'remark': $scope.remark,
      'otherRemark': $scope.otherRemark,
      'activityRemark': $scope.activityRemark,
      'costType': costType
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //后端佣金到账
  $scope.backRabite = function() {
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.hdyjdaozhang = {
      'id': $scope.id,
      'oBackStatus': '311',
      'costType': costType
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.hdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //前端财务结佣
  $scope.isReq = false;
  $scope.frontFinance = function(t) {
    $scope.oRebateType = t; //自提或者结佣
    if($scope.oRebateType == 2) {
      $scope.isReq = true;
    }else{
      $scope.isReq = false;
    }

    if (!$scope.form.$invalid) {
      $scope.costAmount = $scope.item.costAmount;
      $scope.activityFunds = $scope.item.activityFunds;
      $scope.otherFunds = $scope.item.otherFunds;
      $scope.remark = $scope.item.remark;
      $scope.otherRemark = $scope.item.otherRemark;
      $scope.activityRemark = $scope.item.activityRemark;
      $scope.qdcwjieyong = {
        'id': $scope.id,
        'oStatus': '320',
        'oRebateType': $scope.oRebateType,
        'costAmount': $scope.item.costAmount,
        'activityFunds': $scope.item.activityFunds,
        'otherFunds': $scope.item.otherFunds,
        'remark': $scope.item.remark,
         'otherRemark': $scope.item.otherRemark,
        'activityRemark': $scope.item.activityRemark
      };
      if($scope.item.oOwnerId) {
        $scope.qdcwjieyong.oYouDanRebateType = $scope.oRebateType;
        delete $scope.qdcwjieyong.oRebateType;
      }
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项");
    }
  };

  //原先没有成交金额，现在先确认提交成交价 querenCJJ

  $scope.querenCJJ = function() {

    if (!$scope.form.$invalid) {
      $scope.oSellingPrice = $scope.item.oSellingPrice;
      $scope.oTransactionPrice = $scope.item.oTransactionPrice;
      $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
      console.log($scope.oTransactionPrice);
      console.log($scope.oTransactionRebate);

      $scope.qdcwjieyongCJJ = {
        'id': $scope.id,
        'oTransactionPrice': $scope.oTransactionPrice,
        'oTransactionRebate': $scope.oTransactionRebate
      };


      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            //改变判断依据的值
            $scope.item.shiZhuFlag = '1';
            //$route.reload();
            $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
              id: $scope.id,
              s: $scope.s
            });

          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，请联系产品部相关负责人");
        } else {
          newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              //改变判断依据的值
              $scope.item.shiZhuFlag = '1';
              //$route.reload();
              $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
                id: $scope.id,
                s: $scope.s
              });

            }
          });
        }
      }
    }
  };


  //后端财务结佣
  $scope.backFinance = function(t) {
    if(!$scope.item.costAmount){
      alert("请确认结佣金额!");
      return ;
    }
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oBackStatus': '321',
      'costAmount':$scope.item.costAmount,
      'costType': costType
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项")
    }
  };


   //渠道申请后端结佣
  $scope.applyBackFront = function() {
    if(!$scope.item.costType){
      alert("请选择费用类型");
      return ;
    }
    var amount=($scope.item.costPrice * $scope.item.oAmount / 100);
    if(!$scope.item.oBackTransactionPrice){
      $scope.item.oBackTransactionPrice=$scope.item.costPrice;
    }
    if(!$scope.item.oBackTransactionRebate){
      $scope.item.oBackTransactionRebate=amount;
    }
     $scope.qdsqjieyong = {
      'id': $scope.id,
      'oBackStatus': '241',
      'userName' : $scope.item.userName,
      'costType': $scope.item.costType,
      'costPrice': $scope.item.costPrice,
      'costAmount': amount,
      'cardNumber': $scope.item.cardNumber ,
      'oBackTransactionPrice' :$scope.item.oBackTransactionPrice,
      'oBackTransactionRebate' :$scope.item.oBackTransactionRebate,
      'bankName': $scope.item.bankName,
      'remark': $scope.item.remark 
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdsqjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项")
    }
  };

  //产品审核后端结佣申请
  $scope.checkBackFront = function(status) {
    var oBackStatus="";
     var reson="审核通过";
      if(status=='yes'){
        //原311修改为261（新增状态  需要产品填写上游结佣）
        oBackStatus='261';   
        reson="";
      }else{
        oBackStatus='231';
        reson="审核未通过";
      }
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oBackStatus': oBackStatus,
      'reson' : reson,
      'costType': costType
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //前端确认返佣
  $scope.comfirmFrontRabite = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '330'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };


  //后端确认返佣
  $scope.comfirmBackRabite = function() {
      var costType = "";
      if($scope.backList && $scope.backList.length>0) {
          costType = $scope.backList[0].costType;
      }
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oBackStatus': '331',
      'costType': costType,
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //结束交易  做这个结束动作时先要判断是否结佣


  $scope.closeTrade = function() {



    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '360'
    }).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2008') {
          alert(json.statusCode + ":后端未走完，请先结束后端操作");
        }else  if (json.statusCode == '2006') {
          alert(json.statusCode + ":报单未审核完成");
        }else  if (json.statusCode == '2012') {
          alert(json.statusCode + ":合同未回收");
        } else {
          alert("出错了:" + json.statusCode);
        }

      } else {
        $route.reload();
      }
    });
  };

  //交易结束  不需要
  $scope.tradeClose = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '370'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //提交有效合同item.receiveContractNum
  $scope.takeEffectiveContract = function() {
    $scope.id = $scope.item.id;
    $scope.receiveContractNum = $scope.item.receiveContractNum;
    $scope.oFrontContractDocument = $scope.item.oFrontContractDocument;
    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oStatus': '350',
      'receiveContractNum': $scope.receiveContractNum,
      'oFrontContractDocument': $scope.oFrontContractDocument
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode == '2006') {
          alert(json.statusCode + "-还有资料未审核通过,提交合同失败");
        } else {
          $location.path("/neworder/chanping/ordermanager/effective/view").search({
            id: $scope.id
          });
        }
      });
    }
  };


  //取消订单
  $scope.cancel = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '999'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };




  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer2 = function() {

    $scope.isShowVisitLayer2 = true;

  }

  //预约失败
  $scope.applyFail = function() {
    //  $scope.isShowVisitLayer2 = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      newOrderService.updateOrderStatusAndOther({
        'id': $scope.id,
        'oStatus': '140',
        'oCancelReason': $scope.oCancelReason
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };


  $scope.isShowTransactionPrice = function(status) {
    return (status == '250') || (status == '310') || (status == '311') || (status == '312') || (status == '313') || (status == '314');
  };

  //标记为无效订单
  $scope.avail = function(status) {
    newOrderService.updateDefriendStatus({
      'id': $scope.id,
      oDefriendStatus: status
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };



  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer = function() {

    $scope.isShowVisitLayer = true;


  }




  //确认订单失败
  $scope.confirmFailure = function() {
    // $scope.isShowVisitLayer = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      $scope.orderFailcfx = {
        'id': $scope.id,
        'oStatus': '888',
        'oCancelReason': $scope.oCancelReason
      }
      newOrderService.updateOrderStatusAndOther($scope.orderFailcfx).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);
faApp.controller('NewOrderQDMListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderQDMListCtrl";
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }
  var hasPage = 'hasPageNewOrderQDM';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.qdmlist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true)


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };


  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07",
    "target": "0"
  };

  newOrderService.queryOrderList($scope.fit).then(function(json) {
    $scope.orderList = json.list || [];
  });

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;

  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.search = function(reload) {
    $scope.config.pageNo = 1;
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件

    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }
    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);

//渠道管理员查询所有订单
faApp.controller('NewOrderQDAListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderQDAListCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }


  var hasPage = 'hasPageNewOrderQDA';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.qdalist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true);


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };

  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07",
    "target": "1"
  };

  newOrderService.queryOrderList($scope.fit).then(function(json) {
    $scope.orderList = json.list || [];
  });

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;
  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };

  $scope.search = function(reload) {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }

    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }
    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  //分配和回收处理
  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.managerOrder = {};

  $scope.fenpeiOrHuishou = function(t) {
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "02";
    $scope.managerOrder.faids = $scope.faids;

    if (t == "1") {
      if ($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != "") {
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            if (json.statusCode == '4001') {
              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if (json.mess != undefined) {
                angular.forEach(json.mess, function(o) {
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if (confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")) {
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json) {
                  if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                  } else {
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            } else {
              alert("出错了:" + json.statusCode);
            }
          } else {
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        }, function(res) {
          alert('网络状态不稳定或超时！');
        });

      } else {
        alert("请选择订单跟进人！");
      }
    } else if (t == '0') {

      var tmpid = "";
      angular.forEach($scope.omu.split(","), function(o, i) {
        if (i == 0) {
          tmpid = o;
        } else {
          if (o != undefined && o != "" && o != tmpid) {
            tmpid = "99";
          }
        }
      });

      if (tmpid != undefined && tmpid != "99") {
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      } else {
        if (confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")) {
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  }

  $scope.getLastSearchConfig();
  $scope.search(true);
}]);

//产品个人查询集合
faApp.controller('NewOrderCPMListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderCPMListCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }
  var hasPage = 'hasPageNewOrderCPM';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.cpmlist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true)


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };


  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07"
  };

  //newOrderService.queryOrderList($scope.fit).then(function(json){
  // console.log($scope.fit);
  //   $scope.orderList=json.list || [];
  //});

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;

  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.search = function() {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件

    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }
  //审核不通过
  $scope.isInvestigateNo = function(id) {
      newOrderService.updateOrderStatusAndOther({
        'id': id,
        'oStatus': '140',
        'oCancelReason': '审核未通过'
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
    //审核通过
  $scope.isInvestigateYes = function(id) {
    newOrderService.updateOrderStatusAndOther({
      'id': id,
      'oStatus': '130',
      'oCancelReason': 'aa'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  }
  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }
    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          ("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);

//产品所有订单查询集合
faApp.controller('NewOrderCPAListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderCPAListCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }
  var hasPage = 'hasPageNewOrderCPA';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.cpalist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true)


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };


  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07"
  };

  //newOrderService.queryOrderList($scope.fit).then(function(json){
  // console.log($scope.fit);
  //   $scope.orderList=json.list || [];
  //});

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;

  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.search = function() {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件

    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }
  //审核不通过
  $scope.isInvestigateNo = function(id) {
      newOrderService.updateOrderStatusAndOther({
        'id': id,
        'oStatus': '140',
        'oCancelReason': '审核未通过'
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
    //审核通过
  $scope.isInvestigateYes = function(id) {
    newOrderService.updateOrderStatusAndOther({
      'id': id,
      'oStatus': '130',
      'oCancelReason': 'aa'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  }
  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }

    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);

//财务所有订单查询集合
faApp.controller('NewOrderCWAListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderCWAListCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }
  var hasPage = 'hasPageNewOrderCWA';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.cwalist($scope.config).then(function(json) {
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true)


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };


  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07"
  };

  //newOrderService.queryOrderList($scope.fit).then(function(json){
  // console.log($scope.fit);
  //   $scope.orderList=json.list || [];
  //});

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;

  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.search = function() {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件

    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }

    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);

//财务管理员所有订单查询集合
faApp.controller('NewOrderCWGLYListCtrl', ['$scope', 'newOrderService', 'orderManagerService', '$location', '$controller', '$route', '$routeParams', 'sessionService', function($scope, newOrderService, orderManagerService, $location, $controller, $route, $routeParams, sessionService) {
  $scope.ctrlName = "NewOrderCWGLYListCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.list = [];
  $scope.productCreatByList = [];
  $scope.loading = true;
  $scope.configt = {};
  $scope.m = $routeParams.m;
  $scope.paramclear=$routeParams.paramclear;
  if($scope.paramclear=='true'){
    $scope.clearLastSearchConfig();
  }
  var hasPage = 'hasPageNewOrderCWGLY';

  //产品负责人

  newOrderService.querycpfzr($scope.configt).then(function(json) {
    $scope.productCreatByList = json.list || [];
    $scope.loading = false;
  });

  $scope.$watch('config', function() {
    if ($scope.watchIsChange()) {
      newOrderService.cwaglylist($scope.config).then(function(json) {
        $scope.list = json.orderList;

        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  }, true)


  $scope.config = {
    "pageSize": 20,
    "pageNo": 1,
    "orderCtrType": $scope.m
  };


  $scope.pageChanged = function() {
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit = {
    "oPType": "02,03,06,07"
  };

  //newOrderService.queryOrderList($scope.fit).then(function(json){
  // console.log($scope.fit);
  //   $scope.orderList=json.list || [];
  //});

  $scope.isShowOrder = false;
  //点击事件显示消息
  $scope.changeShow = function() {
    $scope.isShowOrder = true;

  }

  //显示样式改变
  $("#changecss").mouseover(function() {
    $("#changecss").removeClass("markyanse");
    $("#changecss").addClass("changeCSS");
  });
  $("#changecss").mouseleave(function() {
    $("#changecss").addClass("markyanse");
    $("#changecss").removeClass("changeCSS");
  });

  $scope.changeProductType = function() {
    var tmp = "";
    $("[name='ptype']").each(function() {
      if ($(this).attr("checked") == "checked") {
        tmp += $(this).val() + ",";
      }
    });
    if (tmp.length > 0) {
      tmp = tmp.substring(0, tmp.length - 1);
    } else {
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
      //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    $scope.search();
  };
  $scope.search = function() {
    $scope.searchMap.isnoManagerUser = "";
    if ($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser") {
      $scope.searchMap.isnoManagerUser = "yes";
    }
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件

    if ($scope.searchMap.oPType == '') {
      $scope.searchMap.oPType = "02,03,06,07";
    }
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;

    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, type, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&pType=' + type;
      $location.url(url);
    }
  }

  $scope.toUploadPage = function(pId, oId, pType, oType, address){
    if(pId){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      if(oType=='02'){
        oType="01";
      }else if(oType=='03'){
        oType="02";
      }

      var url = address + 'pId=' + pId + '&oId=' + oId + '&pType=' + pType + '&oType=' + oType;
      $location.url(url);
    }
  }

  if ($scope.orderManagerUserList == undefined) {
    var access = sessionService.getItem("user.access", "");
    var tmp = "";
    if (access == "all") {
      tmp = "in";
    } else {
      angular.forEach(access.split(","), function(o) {

        if (o.indexOf("queryOrderManagerUsersList.shtml") == 0) {
          tmp = "in";
        }
      });
    }

    if (tmp != undefined && tmp.length) {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({
            userId: "isnoManagerUser",
            username: "无跟进人订单"
          });
        }
      });
    }
  }

  $scope.chkAllOrderList = function() {
    if ($("#chkAllOrderList").attr("checked") == "checked") {
      $("[name='chkOrderList']").attr("checked", "checked");
    } else {
      $("[name='chkOrderList']").attr("checked", false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";

  $scope.orderDoOrder = function(t) {
    chooseOrderList(t);
    if ($scope.chooseOrderId != undefined && $scope.chooseOrderId != "") {
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    } else {
      alert("请选择订单！");
      return;
    }

    if (t != undefined && t != "" && t == "1") {
      orderManagerService.list({
        "pageSize": 9999,
        "pageNo": 1
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t) {
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i) {
      if ($(this).attr("checked") == "checked") {
        if (t == 1 && $(this).attr("omu")) {
          alert("请选择没有订单跟进人的订单！");
          $scope.chooseOrderId = -1;
          return false;
        } else if (t == 0 && !$(this).attr("omu")) {
          alert("请选择有订单跟进人的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }

        if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);

//渠道、产品、财务员工 详情
faApp.controller('NewOrderQDViewCtrl', ['$scope', 'newOrderService', '$location', '$controller', '$route', '$routeParams', '$filter', function($scope, newOrderService, $location, $controller, $route, $routeParams, $filter) {
  $scope.ctrlName = "NewOrderQDViewCtrl";
  $controller('BaseListCtrl', {
    $scope: $scope
  });

  $scope.isShowVisitLayer = false;
  $scope.isShowVisitLayer2 = false;
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {
    'id': $scope.id
  };
  $scope.pType = $routeParams.pType;
  $scope.s = $routeParams.s;
  $scope.m=$routeParams.m;
  $scope.role=$routeParams.role;

  newOrderService.queryOrderXiangqing({
    'id': $scope.id
  }).then(function(json) {
    $scope.item = json.orderDetail || {};
    $scope.item.wanAmount = $scope.item.oAmount/10000;
    $scope.loading = false;

  });



  $scope.onUploadFile({

    showMessage: function(m) {
      alert(m);
    },
    onComplete: function(f, response) {
      if (response.statusCode == "0000") {

        if ($scope.s == '1') {
          //（财务后端）上传打款凭条
          //alert(1);
          $scope.item.oBackContractDocument = App.staticHost + response.attribute.fileUrl;
        } else if ($scope.s == '2') {
          //财务上传打款凭条
          $scope.item.oContractDocument = App.staticHost + response.attribute.fileUrl;
          // alert(2);
        } else if ($scope.s == '3') {

          //上传合同凭证
          //alert(3);
          $scope.item.oFrontContractDocument = App.staticHost + response.attribute.fileUrl;
        }

        //$scope.picAddre = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });


  //审核不通过
  $scope.isInvestigateNo = function(id) {
      newOrderService.updateOrderStatusAndOther({
        'id': id,
        'oStatus': '140',
        'oCancelReason': '审核未通过'
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
    //审核通过
  $scope.isInvestigateYes = function(id) {
    newOrderService.updateOrderStatusAndOther({
      'id': id,
      'oStatus': '130',
      'oCancelReason': 'aa'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  }
  //预约成功
  $scope.applySuccess = function(v) {

    if(v){
      $scope.oCName = $scope.item.oCName;
      $scope.oAmount = $scope.item.wanAmount*10000;
      $scope.uInfo = {
        'id': $scope.id,
        'oCName':$scope.oCName,
        'oAmount':$scope.oAmount,
        'oStatus': '110',
        'updateInfo':true
      };
      newOrderService.updateOrderStatusAndOther($scope.uInfo).then(function(json) {
        if (json.statusCode) {
          switch (json.statusCode){
            case '2302':alert('订单购买金额小于起购金额')
              break;
            case '2304':alert('累进金额错误')
              break;
            case  '2303':alert('订单购买金额大于预售金额')
              break;
          };
        } else {
          $route.reload();
        }
      });
      return;
    }
    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;


    $scope.oSellingPrice = $scope.item.oSellingPrice;
    $scope.oBackSellingPrice = $scope.item.oBackSellingPrice;

    $scope.oBackTransactionPrice = $scope.item.oBackTransactionPrice;
    $scope.oTransactionPrice = $scope.item.oTransactionPrice;
    $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
    if ($scope.item.oBackCorePrice == undefined) {
      $scope.oBackTransactionRebate = $scope.item.oTransactionRebate;
    } else {
      $scope.oBackTransactionRebate = $scope.item.oBackTransactionPrice * $scope.item.oAmount / 100;
    }

    $scope.oKnotType = $scope.item.oKnotType
    $scope.yuyuesuccess = {
      'id': $scope.id,
      'oCName':$scope.oCName,
      'oAmount':$scope.oAmount,
      'oStatus': '130',
      'oTransactionPrice': $scope.oTransactionPrice,
      'oBackTransactionPrice': $scope.oBackTransactionPrice,
      'oTransactionRebate': $scope.oTransactionRebate,
      'oBackTransactionRebate': $scope.oBackTransactionRebate,
      'oKnotType': $scope.oKnotType,
    };
    if (!$scope.form.$invalid) {
      //有没有后端，没有就不让输入，有就输入
      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            $route.reload();
          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，待产品经理审核");
          $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        } else if($scope.oBackTransactionPrice > $scope.oBackSellingPrice){
            alert("后端成交价大于后端核心价，待产品经理审核");
            $scope.yuyuesuccess.oStatus = '120';//改变预约成功为审核状态
        }
        $scope.x = $scope.selectedId
        newOrderService.updateOrderStatusAndOther($scope.yuyuesuccess).then(function(json) {
              if (json.statusCode) {
                alert("出错了:" + json.statusCode);
              } else {
                $route.reload();
              }
        });
      }
    }
  };
  //已寄出有效合同
  $scope.sendContract = function() {

    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '210'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };


  //确认已签约打款
  $scope.process = function(status) {

    $scope.qryqydangkang = {
      'id': $scope.id,
      'oStatus': '220'
    };

    newOrderService.updateOrderStatusAndOther($scope.qryqydangkang).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2006') {
          alert("还有资料未审核通过不能返佣!!!");
        } else {
          alert("出错了:" + json.statusCode);
        }
      } else {
        $route.reload();
      }
    });
  };


  //确认打款
  $scope.comfirmPay = function() {

    if ($scope.item.oBackTransactionPrice == undefined || $scope.item.oBackTransactionPrice < 0) {
      $scope.qrdangkang = {
        'id': $scope.id,
        'oStatus': '240',
        'oBackStatus': '361'
      };
    } else {
      $scope.qrdangkang = {
        'id': $scope.id,
        'oStatus': '240',
        'oBackStatus': '241'
      };
    }
    newOrderService.updateOrderStatusAndOther($scope.qrdangkang).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };



  //前端佣金到账
  $scope.frontRabite = function() {

    $scope.upstreamHitman = $scope.item.upstreamHitman;
    $scope.upstreamHitmanNum = $scope.item.upstreamHitmanNum;
    $scope.sendContractNum = $scope.item.sendContractNum;
    $scope.confirmForntAmount = $scope.item.confirmForntAmount;
    $scope.confirmOtherAmount = $scope.item.confirmOtherAmount;
    $scope.comfirmOtherSectionDesc = $scope.item.comfirmOtherSectionDesc;


    $scope.qdyjdaozhang = {
      'id': $scope.id,
      'oStatus': '310',
      'upstreamHitman': $scope.upstreamHitman,
      'upstreamHitmanNum': $scope.upstreamHitmanNum,
      'sendContractNum': $scope.sendContractNum,
      'confirmForntAmount': $scope.confirmForntAmount,
      'confirmOtherAmount': $scope.confirmOtherAmount,
      'comfirmOtherSectionDesc': $scope.comfirmOtherSectionDesc
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //后端佣金到账
  $scope.backRabite = function() {
    if ($scope.item.oBackStatus != '241') {
      $scope.confirmBackAmount = 0;
    } else {
      $scope.confirmBackAmount = $scope.item.confirmBackAmount;
    }

    $scope.hdyjdaozhang = {
      'id': $scope.id,
      'oBackStatus': '311',
      'confirmBackAmount': $scope.confirmBackAmount
    };
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.hdyjdaozhang).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  //前端财务结佣
  $scope.isReq = false;
  $scope.frontFinance = function(t) {
    $scope.oRebateType = t; //自提或者结佣
    if($scope.oRebateType == 2) {
      $scope.isReq = true;
    }else{
      $scope.isReq = false;
    }

    if($scope.oRebateType == 2 && !$scope.item.oRebateBankId && !$scope.item.oRebateBankCardHolder && !$scope.item.oRebateBankCardNumber) {
      alert('请填写完整表单和线下结佣必填项');
      return;
    }

    if (!$scope.form.$invalid) {
      $scope.oFinanceFrontRebate = $scope.item.oFinanceFrontRebate;
      $scope.oActivityAmount = $scope.item.oActivityAmount;
      $scope.oPlaySectionDesc = $scope.item.oPlaySectionDesc;
      $scope.oFinanceOtherAmount = $scope.item.oFinanceOtherAmount;
      $scope.oFinancOtherAmountDesc = $scope.item.oFinancOtherAmountDesc;
      $scope.oContractDocument = $scope.item.oContractDocument;

      $scope.oRebateBankId = $scope.item.oRebateBankId || '';
      $scope.oRebateBankCardHolder = $scope.item.oRebateBankCardHolder || '';
      $scope.oRebateBankCardNumber = $scope.item.oRebateBankCardNumber || '';

      $scope.qdcwjieyong = {
        'id': $scope.id,
        'oStatus': '320',
        'oRebateType': $scope.oRebateType,
        'oFinanceFrontRebate': $scope.oFinanceFrontRebate,
        'oActivityAmount': $scope.oActivityAmount,
        'oPlaySectionDesc': $scope.oPlaySectionDesc,
        'oFinanceOtherAmount': $scope.oFinanceOtherAmount,
        'oFinancOtherAmountDesc': $scope.oFinancOtherAmountDesc,
        'oContractDocument': $scope.oContractDocument,
        'oTransactionPrice': $scope.oTransactionPrice,
        'oTransactionRebate': $scope.oTransactionRebate,

        'oRebateBankId': $scope.oRebateBankId,
        'oRebateBankCardHolder': $scope.oRebateBankCardHolder,
        'oRebateBankCardNumber': $scope.oRebateBankCardNumber
      };
      if($scope.item.oOwnerId) {
        $scope.qdcwjieyong.oYouDanRebateType = $scope.oRebateType;
        delete $scope.qdcwjieyong.oRebateType;
      }
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项");
    }
  };

  //原先没有成交金额，现在先确认提交成交价 querenCJJ

  $scope.querenCJJ = function() {

    if (!$scope.form.$invalid) {
      $scope.oSellingPrice = $scope.item.oSellingPrice;
      $scope.oTransactionPrice = $scope.item.oTransactionPrice;
      $scope.oTransactionRebate = $scope.item.oTransactionPrice * $scope.item.oAmount / 100;
      console.log($scope.oTransactionPrice);
      console.log($scope.oTransactionRebate);

      $scope.qdcwjieyongCJJ = {
        'id': $scope.id,
        'oTransactionPrice': $scope.oTransactionPrice,
        'oTransactionRebate': $scope.oTransactionRebate
      };


      //是否协议价、是就不做处理，然后让流程继续往下走，如果不是就按照判断逻辑来走。
      if ($scope.item.isAgreement == '1') {
        newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
          if (json.statusCode) {
            alert("出错了:" + json.statusCode);
          } else {
            //改变判断依据的值
            $scope.item.shiZhuFlag = '1';
            //$route.reload();
            $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
              id: $scope.id,
              s: $scope.s
            });

          }
        });
      } else {
        //如果成交价大于渠道核心价的处理，不大于才能预约成功
        if ($scope.oTransactionPrice > $scope.oSellingPrice) {
          alert("成交价大于核心价，请联系产品部相关负责人");
        } else {
          newOrderService.updateOrderStatusAndOther($scope.qdcwjieyongCJJ).then(function(json) {
            if (json.statusCode) {
              alert("出错了:" + json.statusCode);
            } else {
              //改变判断依据的值
              $scope.item.shiZhuFlag = '1';
              //$route.reload();
              $location.path("/neworder/caiwu/ordermanager/incomplete/view").search({
                id: $scope.id,
                s: $scope.s
              });

            }
          });
        }
      }
    }
  };


  //后端财务结佣
  $scope.backFinance = function(t) {
    $scope.oBackRebateType = t; //自提或者结佣
    if($scope.oBackRebateType == 2) {
      $scope.isReq = true;
    }else{
      $scope.isReq = false;
    }
    if($scope.oBackRebateType == 2 && !$scope.item.oBackRebateBankId && !$scope.item.oBackRebateBankCardHolder && !$scope.item.oBackRebateBankCardNumber) {
      alert('请填写完整表单和线下结佣必填项');
      return;
    }
    $scope.oFinanceBackRebate = $scope.item.oFinanceBackRebate;
    $scope.oBackContractDocument = $scope.item.oBackContractDocument;

    $scope.oBackRebateBankId = $scope.item.oBackRebateBankId;
    $scope.oBackRebateBankCardHolder = $scope.item.oBackRebateBankCardHolder;
    $scope.oBackRebateBankCardNumber = $scope.item.oBackRebateBankCardNumber;

    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oBackStatus': '321',
      'oBackRebateType' : $scope.oBackRebateType,
      'oFinanceBackRebate': $scope.oFinanceBackRebate,
      'oBackContractDocument': $scope.oBackContractDocument,

      'oBackRebateBankId': $scope.oBackRebateBankId || '',
      'oBackRebateBankCardHolder': $scope.oBackRebateBankCardHolder || '',
      'oBackRebateBankCardNumber': $scope.oBackRebateBankCardNumber || ''
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }else{
      alert("请填写必填项")
    }
  };

  //前端确认返佣
  $scope.comfirmFrontRabite = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '330'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };



  //后端确认返佣
  $scope.comfirmBackRabite = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oBackStatus': '331'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //结束交易  做这个结束动作时先要判断是否结佣


  $scope.closeTrade = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '360'
    }).then(function(json) {
      if (json.statusCode) {
        if (json.statusCode == '2008') {
          alert(json.statusCode + ":后端未走完，请先结束后端操作");
        } else {
          alert("出错了:" + json.statusCode);
        }

      } else {
        $route.reload();
      }
    });
  };

  //交易结束  不需要
  $scope.tradeClose = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '370'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };

  //提交有效合同item.receiveContractNum
  $scope.takeEffectiveContract = function() {
    $scope.id = $scope.item.id;
    $scope.receiveContractNum = $scope.item.receiveContractNum;
    $scope.oFrontContractDocument = $scope.item.oFrontContractDocument;
    $scope.qdcwjieyong = {
      'id': $scope.id,
      'oStatus': '350',
      'receiveContractNum': $scope.receiveContractNum,
      'oFrontContractDocument': $scope.oFrontContractDocument
    }
    if (!$scope.form.$invalid) {
      newOrderService.updateOrderStatusAndOther($scope.qdcwjieyong).then(function(json) {
        if (json.statusCode == '2006') {
          alert(json.statusCode + "-还有资料未审核通过,提交合同失败");
        } else {
          $location.path("/neworder/chanping/ordermanager/effective/view").search({
            id: $scope.id
          });
        }
      });
    }
  };


  //取消订单
  $scope.cancel = function() {
    newOrderService.updateOrderStatusAndOther({
      'id': $scope.id,
      'oStatus': '999'
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };




  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer2 = function() {

    $scope.isShowVisitLayer2 = true;

  }

  //预约失败
  $scope.applyFail = function() {
    //  $scope.isShowVisitLayer2 = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      newOrderService.updateOrderStatusAndOther({
        'id': $scope.id,
        'oStatus': '140',
        'oCancelReason': $scope.oCancelReason
      }).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };


  $scope.isShowTransactionPrice = function(status) {
    return (status == '250') || (status == '310') || (status == '311') || (status == '312') || (status == '313') || (status == '314');
  };

  //标记为无效订单
  $scope.avail = function(status) {
    newOrderService.updateDefriendStatus({
      'id': $scope.id,
      oDefriendStatus: status
    }).then(function(json) {
      if (json.statusCode) {
        alert("出错了:" + json.statusCode);
      } else {
        $route.reload();
      }
    });
  };



  //$scope.visitList = [];
  /**回访**/
  $scope.showVisitLayer = function() {

    $scope.isShowVisitLayer = true;


  }




  //确认订单失败
  $scope.confirmFailure = function() {
    // $scope.isShowVisitLayer = true;
    $scope.oCancelReason = $scope.item.oCancelReason;
    if (!$scope.itll.$invalid) {
      $scope.orderFailcfx = {
        'id': $scope.id,
        'oStatus': '888',
        'oCancelReason': $scope.oCancelReason
      }
      newOrderService.updateOrderStatusAndOther($scope.orderFailcfx).then(function(json) {
        if (json.statusCode) {
          alert("出错了:" + json.statusCode);
        } else {
          $route.reload();
        }
      });
    }
  };

  $scope.getLastSearchConfig();
  $scope.search(1);
}]);


faApp.controller('NewsAddCtrl',['$scope','$location','$controller','$route','$filter','$routeParams','newsService',function($scope,$location,$controller,$route,$filter,$routeParams,newsService) {

  $scope.loading = true;
  $scope.news = {
    fpJpushSendType: '02',
    fpJpushMsgType: '01'
  };
  $scope.id = $routeParams.id;

  if($scope.id){
    newsService.newsList({pageSize:1, pageNo:1, id:$scope.id}).then(function(json){
      if (json.statusCode){
        alert(json.statusCode);
      }else{
        $scope.news = json.list[0];

        $scope.news.fpJpushRedrict = decodeURI(utf8to16(base64decode($scope.news.fpJpushRedrict)));

        if($scope.news.fpJpushSendType == '02'){
          $scope.news.fpJpushSendTimeStr = $filter("date")($scope.news.fpJpushSendTime, "yyyy-MM-ddTHH:mm");

          console.log($scope.news.fpJpushSendTimeStr);
          console.log($scope.news.fpJpushSendTime);
        }
      }
    });
  }

  $scope.save = function(){

    if (!$scope.form.$invalid){
      if($scope.news.fpJpushSendTimeStr){
        $scope.news.fpJpushSendTime = $filter("date")($scope.news.fpJpushSendTimeStr, "yyyy-MM-dd HH:mm:ss");
        $scope.news.fpJpushSendTimeStr = '';
      }

      $scope.news.fpJpushRedrict = base64encode(utf16to8(encodeURI($scope.news.fpJpushRedrict)));

      var p = {};
      if($scope.id){
        p = newsService.newsEdit;
      }else{
        p = newsService.newsAdd;
      }

      p($scope.news).then(function(json){
        if (json.statusCode){
          if(json.statusCode == '2002'){
            alert('参数缺失！');
          }else{
            alert(json.statusCode);
          }
        }else{
          alert(($scope.id ? '编辑' : '添加') + '成功！');
          $location.path("/news/list");
        }
      });
    }
  }
  
}]);

faApp.controller('NewsListCtrl',['$scope','$location','$controller','$route','newsService',function($scope,$location,$controller,$route,newsService) {
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.loading = true;

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.newsList = {};

  $scope.$watch('config',function(){
    newsService.newsList($scope.config).then(function(json){
      $scope.newsList = json.list;

      angular.forEach($scope.newsList, function(o){
        if(o.fpJpushRedrict){
          o.fpJpushRedrict = decodeURI(utf8to16(base64decode(o.fpJpushRedrict)));
        }
      });

      $scope.pager = json.pager;
    });
  },true);
  
  $scope.deleteNews = function(id){
    if(id){
      if(confirm('确定要删除吗！')){
        newsService.newsDelete({id: id}).then(function(json){
          if (json.statusCode){
            alert(json.statusCode);
          }else{
            $route.reload();
          }
        });
      }
    }
  }

}]);

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
  -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
  -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
);
// 编码的方法
function base64encode(str) {
  var out, i, len;
  var c1, c2, c3;
  len = str.length;
  i = 0;
  out = "";
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2);
      out += base64EncodeChars.charAt((c1 & 0x3) << 4);
      out += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      out += base64EncodeChars.charAt(c1 >> 2);
      out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      out += base64EncodeChars.charAt((c2 & 0xF) << 2);
      out += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    out += base64EncodeChars.charAt(c1 >> 2);
    out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    out += base64EncodeChars.charAt(c3 & 0x3F);
  }
  return out;
}

// 解码的方法
function base64decode(str) {
  var c1, c2, c3, c4;
  var i, len, out;
  len = str.length;
  i = 0;
  out = "";
  while (i < len) {
    do {
      c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
    } while (i < len && c1 == -1);
    if (c1 == -1)
      break;

    do {
      c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
    } while (i < len && c2 == -1);
    if (c2 == -1)
      break;
    out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

    do {
      c3 = str.charCodeAt(i++) & 0xff;
      if (c3 == 61)
        return out;
      c3 = base64DecodeChars[c3];
    } while (i < len && c3 == -1);
    if (c3 == -1)
      break;
    out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

    do {
      c4 = str.charCodeAt(i++) & 0xff;
      if (c4 == 61)
        return out;
      c4 = base64DecodeChars[c4];
    } while (i < len && c4 == -1);
    if (c4 == -1)
      break;
    out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
  }
  return out;
}

function utf16to8(str) {
  var out, i, len, c;
  out = "";
  len = str.length;
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
      out += str.charAt(i);
    } else if (c > 0x07FF) {
      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    } else {
      out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    }
  }
  return out;
}

function utf8to16(str) {
  var out, i, len, c;
  var char2, char3;
  out = "";
  len = str.length;
  i = 0;
  while (i < len) {
    c = str.charCodeAt(i++);
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += str.charAt(i - 1);
        break;
      case 12:
      case 13:
        // 110x xxxx   10xx xxxx
        char2 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = str.charCodeAt(i++);
        char3 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }
  return out;
}
faApp.controller('OrderListCtrl',['$scope','orderService','exportService','orderManagerService','$location','$controller','$route','$routeParams','sessionService',function($scope,orderService,exportService,orderManagerService,$location,$controller,$route,$routeParams,sessionService) {
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.routet=$routeParams.t;
  if(!$scope.routet){
    $scope.routet="02,03";
  }
  $scope.list = [];
  $scope.loading = true;
	$scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      orderService.list($scope.config).then(function(json){
        $scope.list = json.orderList || [];
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
    "oPType":$scope.routet
	};

	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit={"oPType":"02,03"};

  orderService.queryOrderList($scope.fit).then(function(json){
    // console.log(json.list);
    $scope.orderList=json.list || [];
  });

     //点击事件显示消息
$scope.changeShow=function(){
    $scope.isShowOrder = true;
  
}

//显示样式改变
$("#changecss").mouseover(function(){
$("#changecss").removeClass("markyanse");
  $("#changecss").addClass("changeCSS");
});
$("#changecss").mouseleave(function(){
$("#changecss").addClass("markyanse");
  $("#changecss").removeClass("changeCSS");
});

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
       //默认信托资管
      //tmp="02,03";
    }
    $scope.t = tmp;
     $scope.search();
  };
  $scope.export = function(){
    exportService.exportCSV($scope.config,"ORDER_LIST_EXPORT");
  };
  $scope.search = function(){
    $scope.searchMap.isnoManagerUser = "";
    if($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser"){
      $scope.searchMap.isnoManagerUser = "yes";
    }
      //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if($scope.t != undefined){
      $scope.searchMap.oPType = $scope.t;
    }
    if($scope.searchMap.oPType==''){
      $scope.searchMap.oPType="02,03,07";
    }
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    $scope.config.pageNo = 1;
  };

  if($scope.orderManagerUserList == undefined){
    var access = sessionService.getItem("user.access","");
    var tmp = "";
    if (access == "all"){
       tmp = "in";
    }else{
      angular.forEach(access.split(","),function(o){
        
        if(o.indexOf("queryOrderManagerUsersList.shtml") == 0){
          tmp = "in";
        }
      });
    }

    if(tmp != undefined && tmp.length){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({userId:"isnoManagerUser",username:"无跟进人订单"});
        }
      });
    }
  }

  $scope.chkAllOrderList = function(){
    if($("#chkAllOrderList").attr("checked") == "checked"){
      $("[name='chkOrderList']").attr("checked","checked");
    }else{
      $("[name='chkOrderList']").attr("checked",false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";
  
  $scope.orderDoOrder = function(t){
    chooseOrderList(t);
    if($scope.chooseOrderId != undefined && $scope.chooseOrderId != ""){
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    }else{
      alert("请选择订单！");
      return;
    }

    if(t != undefined && t != "" && t == "1"){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t){
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i){
      if($(this).attr("checked") == "checked"){
        if(t == 1 && $(this).attr("omu")){
          alert("请选择没有订单管理员的订单！");
          $scope.chooseOrderId = -1;
          return false;
        }else if(t == 0 && !$(this).attr("omu")){
          alert("请选择有订单管理员的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }
        
        if($(this).attr("value") != undefined && $(this).attr("value") != ""){
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };
  
  $scope.managerOrder = {};

  $scope.fenpeiOrHuishou = function(t){
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "02";
    $scope.managerOrder.faids = $scope.faids;
 
    if(t == "1"){
      if($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != ""){
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
          if (json.statusCode){
            if(json.statusCode == '4001'){
              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if(json.mess != undefined){
                angular.forEach(json.mess, function(o){
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if(confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")){
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
                  if (json.statusCode){
                    alert("出错了:" + json.statusCode);
                  }else{
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            }else{
              alert("出错了:" + json.statusCode);
            }
          }else{
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        },function(res){
          alert('网络状态不稳定或超时！');
        });

      }else{
        alert("请选择订单管理员！");
      }
    }else if(t == '0'){

      var tmpid = "";
      angular.forEach($scope.omu.split(","),function(o,i){
        if(i == 0){
          tmpid = o;
        }else{
          if(o != undefined && o != "" && o != tmpid){
            tmpid = "99";
          }
        }
      });

      if(tmpid != undefined && tmpid != "99"){
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      }else{
        if(confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")){
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
            if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  }

}]);


faApp.controller('OrderViewCtrl',['$scope','orderService','$location','$controller','$route','$routeParams','$filter',function($scope,orderService,$location,$controller,$route,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {'id':$scope.id};
  $scope.pType=$routeParams.pType;
  orderService.query({orderId:$scope.id}).then(function(json){
    $scope.item = json.orderDetail || {};
    $scope.loading = false;
    
  });
  
  $scope.process = function(status){
    $scope.review.oStatus = status ? status : $filter('orderNextStatusRender')($scope.item.oStatus);
    orderService.edit($scope.review).then(function(json){
      if (json.statusCode){
        if(json.statusCode=='2006'){
          alert("还有资料未审核通过不能返佣!!!");
        }else if(json.statusCode=='2305'){
          alert("超募，请查看是否超出本期募集规模!!!");
        }else{
          alert("出错了:" + json.statusCode);
        }
      }else{
        $route.reload();
      }
    });
  };
  
  $scope.cancel = function(){
    orderService.edit({'id':$scope.id,'oStatus':'999'}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
  
  $scope.applyFail = function(){
    orderService.edit({'id':$scope.id,'oStatus':'140'}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
  
  $scope.isShowTransactionPrice = function(status){
    return (status == '250')
      || (status == '310')
      || (status == '311')
      || (status == '312')
      || (status == '313')
      || (status == '314')
      ;
  };
  
  $scope.avail = function(status){
    orderService.updateDefriendStatus({'id':$scope.id,oDefriendStatus:status}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };

}]);



faApp.controller('OrderFollowUpListCtrl',['$scope','orderFollowUpService','$location','$controller','$route',function($scope,orderFollowUpService,$location,$controller,$route) {
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      orderFollowUpService.list($scope.config).then(function(json){
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  },true)

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "orderType":"02"
  };



  $scope.isShowOrderManagerLayer = false;
  $scope.orderList = [];
  
    //点击事件
$scope.changeShowOrderManagerLayer=function(){
  $scope.isShowOrderManagerLayer = true;
  orderFollowUpService.queryOrderList().then(function(json){
    $scope.orderList=json.list;
  });

}

  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  }; 
  
  $scope.searchMap = {};

  $scope.search = function(){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    $scope.config.pageNo = 1;
  };


}]);


faApp.controller('PEVCOrderListCtrl',['$scope','orderService','orderManagerService','$location','$controller','$route','sessionService',function($scope,orderService,orderManagerService,$location,$controller,$route,sessionService) {
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      orderService.list($scope.config).then(function(json){
        $scope.list = json.orderList;
        $scope.pager = json.page;
        $scope.loading = false;
      });
    }
  },true)

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "oPType":"06"
  };

  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  }; 
  
  $scope.searchMap = {};

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit={};

  orderService.queryOrderList($scope.fit).then(function(json){
    // console.log(json.list);
    $scope.orderList=json.list || [];
  });

     //点击事件显示消息
$scope.changeShow=function(){
    $scope.isShowOrder = true;
  
}

//显示样式改变
$("#changecss").mouseover(function(){
$("#changecss").removeClass("markyanse");
  $("#changecss").addClass("changeCSS");
});
$("#changecss").mouseleave(function(){
$("#changecss").addClass("markyanse");
  $("#changecss").removeClass("changeCSS");
});
  $scope.search = function(){
    $scope.searchMap.isnoManagerUser = "";
    if($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser"){
      $scope.searchMap.isnoManagerUser = "yes";
    }
    $scope.searchMap.oPType = "06";
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    $scope.config.pageNo = 1;
  };

  if($scope.orderManagerUserList == undefined){
   var access = sessionService.getItem("user.access","");
    var tmp = "";
    if (access == "all"){
       tmp = "in";
    }else{
      angular.forEach(access.split(","),function(o){
        
        if(o.indexOf("queryOrderManagerUsersList.shtml") == 0){
          tmp = "in";
        }
      });
    }

    if(tmp != undefined && tmp.length){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({userId:"isnoManagerUser",username:"无跟进人订单"});
        }
      });
    }
  }

  $scope.chkAllOrderList = function(){
    if($("#chkAllOrderList").attr("checked") == "checked"){
      $("[name='chkOrderList']").attr("checked","checked");
    }else{
      $("[name='chkOrderList']").attr("checked",false);
    }
  }

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";
  
  $scope.orderDoOrder = function(t){
    chooseOrderList(t);
    if($scope.chooseOrderId != undefined && $scope.chooseOrderId != ""){
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    }else{
      alert("请选择订单！");
      return;
    }

    if(t != undefined && t != "" && t == "1"){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t){
    $scope.chooseOrderId = "";
    $scope.faids = "";
    $scope.omu = "";
    $("[name='chkOrderList']").each(function(i){
      if($(this).attr("checked") == "checked"){
        if(t == 1 && $(this).attr("omu")){
          alert("请选择没有订单管理员的订单！");
          $scope.chooseOrderId = -1;
          return false;
        }else if(t == 0 && !$(this).attr("omu")){
          alert("请选择有订单管理员的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }
        
        if($(this).attr("value") != undefined && $(this).attr("value") != ""){
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };
  
  $scope.managerOrder = {};

  $scope.fenpeiOrHuishou = function(t){
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "02";
    $scope.managerOrder.faids = $scope.faids;
 
    if(t == "1"){
      if($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != ""){
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
          if (json.statusCode){
            if(json.statusCode == '4001'){
              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if(json.mess != undefined){
                angular.forEach(json.mess, function(o){
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if(confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")){
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
                  if (json.statusCode){
                    alert("出错了:" + json.statusCode);
                  }else{
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            }else{
              alert("出错了:" + json.statusCode);
            }
          }else{
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        },function(res){
          alert('网络状态不稳定或超时！');
        });

      }else{
        alert("请选择订单管理员！");
      }
    }else if(t == '0'){

      var tmpid = "";
      angular.forEach($scope.omu.split(","),function(o,i){
        if(i == 0){
          tmpid = o;
        }else{
          if(o != undefined && o != "" && o != tmpid){
            tmpid = "99";
          }
        }
      });

      if(tmpid != undefined && tmpid != "99"){
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      }else{
        if(confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")){
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
            if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  }

}]);
faApp.controller('OrderManagerUserListCtrl',['$scope','orderManagerService','$location','$controller','$route',function($scope,orderManagerService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.orderManagerUserList = [];
  $scope.loading = true;

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      orderManagerService.list($scope.config).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList = json.list;
          $scope.pager = json.page;
          $scope.loading = false;
        }
      });
    }
  },true);  

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.editManagerOrderByUser = function(uid){
    if(uid != undefined){
      if(confirm("确认要回收所有订单权限吗？")){
        orderManagerService.editManagerOrderByUser(uid).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            alert("回收成功！");
          }
        });
      }
    }
  }
}]);

faApp.controller('OrderManagerUserAddCtrl',['$scope','orderManagerService','$location','$controller','$route',function($scope,orderManagerService,$location,$controller,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.userNotManager = {};
  $scope.notOrderManagerUserList = [];

  orderManagerService.notOrderManagerUserList().then(function(json){
    if (json.statusCode){
      alert("出错了:" + json.statusCode);
    }else{
      $scope.notOrderManagerUserList = json.list;
    }
  });

  $scope.save = function(){
    if (!$scope.form.$invalid){
      orderManagerService.orderManagerUserAdd($scope.userNotManager).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("添加成功！");
          $route.reload();
        }
      });
    }else{
      alert("请选择人员！");
    }
  }

}]);
faApp.controller('OrderPhoUploadCtrl',['$scope','orderPhoService','$location','$controller','$route','$routeParams',function($scope,orderPhoService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.proOrder={oLocation:''};

  $scope.config = {};
  $scope.config.pType=$routeParams.pType;//05私募
  $scope.config.pId=$routeParams.pId;
  $scope.config.oId=$routeParams.oId;
  $scope.config.oType=$routeParams.oType;//03私募
  orderPhoService.query($scope.config).then(function(json){
    $scope.list=json.list;
    $scope.proOrder.oLocation = json.oLocation;
    //alert($scope.proOrder.oLocation);
    console.log("query phoupload end");
    $scope.loading=false;
  });

$scope.picAddres = [];
$scope.orderPhosStatus = [];
$scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        $scope.picAddres[id] =response.attribute.fileUrl;//App.staticHost + 
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
});


$scope.save=function(){
  if (!$scope.form.$invalid){
    $scope.proOrder.orderPhos=$scope.picAddres.join(",");
    $scope.proOrder.orderPhosStatus=$scope.orderPhosStatus.join(",");
    $scope.proOrder.oId=$scope.config.oId;
    $scope.proOrder.pId=$scope.config.pId;
    $scope.proOrder.pType=$scope.config.pType;
    $scope.proOrder.oType=$scope.config.oType;

    orderPhoService.add($scope.proOrder).then(function(json){
      if(!json.statusCode){
        alert("上传成功");
        $route.reload();
      }else{
        alert("上传失败!!!"+json.statusCode);
      }
    })
  }else{
    alert("还有图片未上传");
  }
}

}]);


faApp.controller('OrderPEVCPhoUploadCtrl',['$scope','orderPhoService','$location','$controller','$route','$routeParams',function($scope,orderPhoService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  
$scope.proOrder={oLocation:''};
  $scope.config = {};
  $scope.config.pType=$routeParams.pType;
  $scope.config.pId=$routeParams.pId;
  $scope.config.oId=$routeParams.oId;
  $scope.config.oType=$routeParams.oType;
  $scope.k=$routeParams.k;
  $scope.role=$routeParams.role;
  $scope.head=$routeParams.head;
  orderPhoService.query($scope.config).then(function(json){
    $scope.list=json.list;
     $scope.proOrder.oLocation = json.oLocation;
     console.log("query PEVCphoupload end");
    $scope.loading=false;
  });
$scope.picAddres = [];
$scope.orderPhosStatus = [];

$scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        $scope.picAddres[id] =response.attribute.fileUrl;//App.staticHost + 
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
});


$scope.save=function(){

    $scope.proOrder.orderPhos=$scope.picAddres.join(",");
    $scope.proOrder.orderPhosStatus=$scope.orderPhosStatus.join(",");
    $scope.proOrder.oId=$scope.config.oId;
    $scope.proOrder.pId=$scope.config.pId;
    $scope.proOrder.pType=$scope.config.pType;
    $scope.proOrder.oType=$scope.config.oType;
    orderPhoService.addPEVC($scope.proOrder).then(function(json){
      if(!json.statusCode){
        alert("上传成功");
        $route.reload();
      }else{
        alert("上传失败!!!"+json.statusCode);
      }
    })
 
}

}]);

faApp.controller('OutProductListCtrl',['$scope','outProductService','$location','$controller','$route','$routeParams','sessionService',function($scope,outProductService,$location,$controller,$route,$routeParams,sessionService) {

 $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.showEstablishaFormFlag=false;
  $scope.showPublishFailFormFlag=false;
  $scope.config={
    "productType":"",
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.param={
    "productType":"",
    "id":"",
    "checkStatus":"",
    "failReson":"",
    "failReson2":"",
  };
  $scope.showResonFlag=false;
  $scope.searchMap = {};
  $scope.config.productType = $routeParams.t;
  $scope.searchMap.productType = $routeParams.t;
  $scope.param.productType = $routeParams.t;

  $scope.changeStatus=function(id,status){
    if($scope.param.failReson==''&&status=='3'){
      if($scope.showEstablishaFormFlag){
        alert("原因必填!!");
      }
      $scope.pId=id;
      $scope.showEstablishaFormFlag=true;
      return;
    }else if($scope.param.failReson2==''&&status=='6'){
      if($scope.showPublishFailFormFlag){
        alert("原因必填!!");
      }
      $scope.pId=id;
      $scope.showPublishFailFormFlag=true;
      return;
    }

    if(confirm("确认此操作？")){
      $scope.param.id=id;
      $scope.param.checkStatus=status;
      if(status=='6'){
        $scope.param.failReson=$scope.param.failReson2;
      }
      outProductService.editOutProduct($scope.param).then(function(json){
        if(json.statusCode=='4002'){
         alert("产品未发布!");
       }else if (json.statusCode=='4003'){
        alert("产品未成立!");
      }else if (json.statusCode=='4003'){
        alert("出错了:" + json.statusCode);
      }else if (json.statusCode=='4004'){
        alert("供应方已被黑名单!");
      }else if (json.statusCode=='4005'){
        alert("供应方不存在!");
      }else if (json.statusCode=='4006'){
        alert("供应方未审核通过!");
      }else if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
       //alert("审核成功!");
       $route.reload();
     }
   });
    }
  }
  $scope.showReson=function(v){
    $scope.showResonFlag=true;
    $scope.showResonfailReson=v;
  }
  $scope.$watch('config',function(){
    outProductService.outProductList($scope.config).then(function(json){
    $scope.list = json.foregroundProductList;
   //处理rate为 json数组
    angular.forEach($scope.list,function(n){   
       if(n.rebateType=='1'){
         if(n.rebateRate.substring(0,1)!="["){
              n.rebateRebateJson=angular.fromJson("["+n.rebateRate+"]");
         }else{
          n.rebateRebateJson=angular.fromJson(n.rebateRate);
         }
       }
    });
    $scope.pager=json.pager;
    $scope.loading = false;
    });
  },true);

  $scope.showProductName=function(productType,id){
    if(id&&(productType=='02'||productType=='03')){
      return 0;
    }else if(productType=='06'&&id){
      return 1;
    }else if(productType=='05'&&id){
      return 2;
    }else {
      return 3;
    }
  }
  $scope.showProductPush=function(productType,id){
    if((productType=='02'||productType=='03')&&!id){
      return 0;
    }else if(productType=='06'&&!id){
      return 1;
    }else if(productType=='05'&&!id){
      return 2;
    }
  }

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.sendEmail=function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){  
        pids += $(this).val() + ",";
      }
    });
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }
      pids = pids.substring(0, pids.length - 1);
      outProductService.sendoutProductEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  }
}]);

faApp.controller('OutProductDetailCtrl',['$scope','outProductService','$location','$controller','$route','$routeParams','sessionService',function($scope,outProductService,$location,$controller,$route,$routeParams,sessionService) {
  $scope.t = $routeParams.type;
  outProductService.outProductDetail($routeParams.id).then(function(json){
    $scope.detail = json.foregroundProductDetail;
    //处理rate为 json数组
       if($scope.detail.rebateType == '1'){
         if($scope.detail.rebateRate.substring(0,1)!="["){
              $scope.detail.rebateRebateJson=angular.fromJson("["+$scope.detail.rebateRate+"]");
         }else{
          $scope.detail.rebateRebateJson=angular.fromJson($scope.detail.rebateRate);
         }
       }

  })  
}]);

faApp.controller('ProductRegexCtrl',['$scope','outProductService','$location','$controller','$route','$routeParams','sessionService',function($scope,outProductService,$location,$controller,$route,$routeParams,sessionService) {
  $scope.t = $routeParams.type;
  $scope.config={
    "pageSize" : 20,
    "pageNo" : 1
  };

  outProductService.productRegexList($scope.config).then(function(json){
    $scope.productRegexList = json.fetchXpath;
  });

  $scope.isShowEdit = '';  

  $scope.productRegexEdit=function(o){
    console.log(o);
    $scope.isShowEdit=o.id;
  }
  $scope.productRegexDoEdit=function(o){
    if(o.xpathRegex==''||o.id==''){
      alert("请输入xpath值");
      return ;
    }
    outProductService.editProductRegex(o).then(function(json){
      $route.reload();
    });
  }

}]);



faApp.controller('PersonalSupplierListCtrl',['$scope','personalSupplierService','exportService','$location','$controller','$route','$routeParams','sessionService',
  function($scope,personalSupplierService,exportService,$location,$controller,$route,$routeParams,sessionService) {
  
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.searchMap = {
    "loginName" : "",
    "name" : "",
    "mobile" : "",
    "companyName" : "",
    "companyAddress" : "",
    "checkStatus" : ""
  };
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.$watch('config',function(){
    personalSupplierService.personalSupplierList($scope.config).then(function(json){
    $scope.productSupplierList = json.productSupplierList;
    $scope.pager = json.pager;
    $scope.loading = false;
    });
  },true) 


  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };
  $scope.exportCsv = function(){
    exportService.exportCSV($scope.searchMap,"PERSONAL_SUPPLIER_LIST_CSV");
  };
}]);



faApp.controller('PersonalSupplierDetailCtrl',['$scope','personalSupplierService','$location','$controller','$route','$routeParams','sessionService',
  function($scope,personalSupplierService,$location,$controller,$route,$routeParams,sessionService) {
  
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.save = {};
  $scope.black = {};
  $scope.visit = {};
  personalSupplierService.PersonalSupplierInfo({id:$scope.id}).then(function(json){
    $scope.bean = json.bean || {};
    $scope.save.companyName = $scope.bean.companyName;
    $scope.save.id = $scope.bean.id;
    $scope.save.companyAddress = $scope.bean.companyAddress;
    $scope.save.companyPosition = $scope.bean.companyPosition;
    $scope.save.emailAddress = $scope.bean.emailAddress;
    $scope.save.auditRemarks = $scope.bean.auditRemarks;
    $scope.save.checkStatus = $scope.bean.checkStatus;

    if($scope.save.checkStatus == '4' || $scope.save.checkStatus == '5'){
      $scope.save.uRole = "2";
    }else if($scope.save.checkStatus == '3'){
      $scope.save.uRole = "99";
    }
    if(!$scope.bean.blackList){
      $scope.bean.blackList = "2";
    }
  });

  $scope.selectLevelType = function(type){
    $scope.save.checkStatus = type;
    $scope.save.uRole = "2";
    $scope.aoMsg = false;
  };
  $scope.selectRoleResult = function(){
    $scope.save.checkStatus = "";
    if ($scope.save.uRole == "99"){
      $scope.save.checkStatus = "3";
    }
  }

  $scope.auditOption = function(){
    if($scope.save.failReson == "3"){
      $scope.aoMsg = true;
    }else{
      $scope.aoMsg = false;
    }
  };

  $scope.personalSupplierSave = function(){
    if (!$scope.certform.$invalid){
      if (!$scope.save.uRole || ($scope.save.uRole == "2" && !$scope.save.checkStatus)){
        alert("请选择评级");
        return;
      }
      if($scope.aoMsg){
        if(!$scope.auditOptionMessage){
          alert("请填写未通过原因！");
          return;
        }
        $scope.save.failReson = $scope.auditOptionMessage;
      }
      personalSupplierService.PersonalSupplierSave($scope.save).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
  $scope.showBlackAddForm = function(id){
    $scope.black.id = id;
    $scope.showBlackAddFormFlag = true;
  };
  $scope.showBlackDelForm = function(id){
    $scope.black.id = id;
     $scope.black.blackList = "2";
    personalSupplierService.PersonalSupplierSave($scope.black).then(function(json){
    if (!json.statusCode){
      $scope.addAlert("操作成功");
      $route.reload();
    }else{
      alert("出错了:" + json.statusCode);
    }  
  });
  };
  $scope.blackAdd = function(){
    if (!$scope.form.$invalid){
      $scope.black.blackList = "1";
     personalSupplierService.PersonalSupplierSave($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
    /**回访**/
  $scope.showVisitLayer = function(id){
    $scope.visit.id = id;
    $scope.visit.faId = id;
    $scope.visit.type = "2";
    personalSupplierService.PersonalSupplierVisit($scope.visit).then(function(json){
      $scope.visitList = json.list;
    });
    $scope.isShowVisitLayer = true;
  }

    $scope.addPersonalSupplierVisit = function(){
    $scope.visit.flagVisit = "1";
        /**修改已拜访状态**/ 
    personalSupplierService.PersonalSupplierSave($scope.visit).then(function(json){
      if (!json.statusCode){
        $scope.addAlert("操作成功");
        $route.reload();
      }else{
        alert("出错了:" + json.statusCode);
      }  
    });

    /**添加拜访**/ 
    personalSupplierService.PersonalSupplierAddVisit($scope.visit).then(function(json){
      if (!json.statusCode){
        personalSupplierService.PersonalSupplierVisit($scope.visit).then(function(json){
          $scope.visitList = json.list;
        });
        $scope.visit.visitRemark = "";
      }else{
        alert("出错了:" + json.statusCode);
      }  
    });
  }
}]);

faApp.controller('PEVCProductListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {   
  $controller('ProductBaseCtrl', {$scope: $scope}); 
  
  $scope.ctrlName = "PEVCProductListCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.products = [];
  $scope.loading = true;
  //获取页面类型，06 pevc
  $scope.t = $routeParams.t;

  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  var hasPage = 'hasPagePEVCProductListCtrl';

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
  };

  $scope.$watch('config',function(){
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    //$scope.config['pTypeList'] ="06";//pevc固定查询06

    productService.queryProductList($scope.config).then(function(json){
      $scope.products = json.list;
      $scope.pager = json.projectDTO;
      $scope.loading = false;
    });
  },true);
  
  $scope.searchMap['orderBy'] = $routeParams.orderBy || '',
  $scope.searchMap['orderByTag'] = $routeParams.orderByTag || '',
  $scope.config['orderBy'] = $routeParams.orderBy || '',
  $scope.config['orderByTag'] = $routeParams.orderByTag || '',
  
  $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }
    
    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
    });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }

  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;
    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    !notsave && $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&t=' + $scope.t;
      $location.url(url);
    }
  }

  $scope.getLastSearchConfig();
  $scope.search();

}]);

faApp.controller('PEVCProductAddCtrl',['$scope', 'productService','reportService','$location','$controller','$timeout','companyService','supplierService','$route','$filter','$routeParams',function($scope,productService,reportService,$location,$controller,$timeout,companyService,supplierService,$route,$filter,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope});

  //$scope.product = {pMinimumAmountTmp:100,pRealSubscriptionAmount:0,pRealSubscriptionShare:0,pType:"05",pInvestType:"01",pPublicArea:"00",pSaleStatus:"03",pPaymentInterestType:"03",pEndEarlyIdentification:"0",pProgressiveAmountTmp:10,fpCorpId:0,fpProjectCorpType:'02'};
  $scope.product = {pMinimumAmountTmp:100,pProgressiveAmountTmp:10,pType:"06",pSaleStatus:"02",pRealSubscriptionAmount:0,pRealSubscriptionShare:0,fpCorpId:0,fpProjectCorpType:'02'};
  $scope.loading = true; 

  $scope.pathText = "新增股权基金产品";
  if($routeParams.id){
    $scope.pathText = "修改股权基金产品"; 
  }
  $scope.outproduct={};
  if($routeParams.outProductId!=undefined){
    $scope.product.outProductId=$routeParams.outProductId;
  }
 if($routeParams.productName!=undefined){
    $scope.product.pName=$routeParams.productName;
    $scope.product.pFullName=$routeParams.productName;
  }
  //默认能竞价
  $scope.product.flagBidding=true;
  
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};
  $scope.pid = $routeParams.id;

  $scope.supplierListOfProduct = [];
  $scope.accessNameOfCompany = "";

  $scope.t = $routeParams.t;

  // 复制产品时，是否同时复制产品解析报告
  $scope.ct = $routeParams.ct;

  // 复制年化及佣金的数据
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.attachs = [];

  // 复制产品解析报告
  $scope.report = {};

  $scope.allTjzls = {};

  if($scope.pid != undefined && $scope.pid.length > 0){
    //如果有值，则说明是点了复制按钮，则根据ID加载产品
    productService.productQuery($scope.pid).then(function(json){
      $scope.product = json.project;
      $scope.product.pLinkCode = $scope.product.pCode;
      $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
      $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
      $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
      $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
      $scope.product.image = $scope.product.pImageUri;
      $scope.product.fpCorpId = "0";
      $scope.product.fpProjectCorpType = "02";
      if($scope.product.tjzls!=undefined){
        angular.forEach($scope.product.tjzls.split(","),function(o){
          $scope.allTjzls[o] = true;  
        }); 
      }
      //PE/VC新增扩展字段
      if($scope.product.projectExpandDTO!= undefined){
          $scope.product.peManageOrg=$scope.product.projectExpandDTO.peManageOrg;
          $scope.product.peOrganizeShape=$scope.product.projectExpandDTO.peOrganizeShape;
          $scope.product.peFundShape=$scope.product.projectExpandDTO.peFundShape;
          $scope.product.peSubscriptionFee=$scope.product.projectExpandDTO.peSubscriptionFee;
          $scope.product.peManagementExpense=$scope.product.projectExpandDTO.peManagementExpense;
          $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
          $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
          $scope.product.peRevenueSharing=$scope.product.projectExpandDTO.peRevenueSharing;
          $scope.product.peCompanyDescription=$scope.product.projectExpandDTO.peCompanyDescription;
          delete $scope.product.projectExpandDTO;
      }
    

      // 复制年化及佣金的数据  
      $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
      $scope.projectRabateList = json.projectRabateList;

      delete $scope.product.pSaleTimeStart;
      delete $scope.product.pSaleTimeEnd;
      delete $scope.product.pEstablishmentTime;
      delete $scope.product.pCode;

      $scope.product.pRealSubscriptionAmount = 0;
      $scope.product.pRealSubscriptionShare = 0;
      //delete $scope.product.pRealSubscriptionAmount;
      //delete $scope.product.pRealSubscriptionShare;


      //复制不需要复制销售进度
      delete $scope.product.pPeriods;
      delete $scope.product.pIssuingScale;
      delete $scope.product.pAllSubscriptionAmountTmp;
      delete $scope.product.pRecruitmentSummary;
      $scope.product.pSaleStatus='03';//复制默认为募集中

    });

    // 加载原产品附件的数据 
    productService.productAttachList($scope.pid).then(function(json){
      $scope.attachs = json.projectAttachmentsList;
    });

    // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
    if($scope.ct){
      reportService.deepAnalyticsDetail($scope.pid).then(function(json){
        if(json.dto){
          $scope.report = json.dto || {};
          delete $scope.report.fpProductId;
          delete $scope.report.fpProductStatus;
          // delete $scope.report.id;
        }
      });
    }
  }

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;  
    });
  });

$scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);

  //$scope.product.pSummary = "<p class='p-c-title'><span style='font-family: 微软雅黑;font-size: 16px;'><a name='mjzh'></a>募集账号：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='cpys'></a>产品优势：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='fxkz'></a>风险控制：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='hkly'></a>还款来源：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='zjyt'></a>资金用途：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='rzf'></a>融资方：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='dbf'></a>担保方：</span></p>";

  $scope.product.pSummary = "<div style='width:1000px;'><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='mjzh'></a>募集账号</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='xmld'></a>项目亮点</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='fxkz'></a>风险控制</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='zjyt'></a>资金用途</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='gltd'></a>管理团队</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='tzcl'></a>投资策略</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='qt'></a>其他</li><li style=''>---输入内容---</li></ul></div>";

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.id = "";
      //新增pe/vc 产品
      $scope.product.pType = "06";
      //$scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pIssuingScale = 0;

      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;

      if($scope.ct && $scope.report.id){
        $scope.product.copyType = "01";
      }
      $scope.product.tjzls=$scope.selectTjzls.join(",");
      productService.productAddPEVC($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          //产品录入成功之后，如果是复制操作则把年化佣金、附件同时保存到数据库。
          if($scope.pid != undefined && $scope.pid.length > 0){
            if($scope.projectAnnualRevenue.length > 0 && $scope.projectRabateList.length > 0){
              $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pCostBackPrice:[],pCoreBackPrice:[],pBackSellingPrice:[],pBackRabateProfit:[]};
              angular.forEach($scope.projectAnnualRevenue,function(o,i){
                //产品ID
                $scope.formData['pId'].push(json.projectDTO.id);
                //返佣类型，01：百分比
                $scope.formData['pRebateType'].push("01");
                //起始金额
                $scope.formData['pStartAmount'].push(o['pStartAmount']);
                // 结束金额
                $scope.formData['pEndAmount'].push(o['pEndAmount']);
                // 预期年化率
                $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
                // 返佣率
                $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
                // 核心价
                $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
                // 成本价
                $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
                // 机构价
                $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);

                $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
                $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
                $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);
                $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);
                // 是否协议
                $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
              });
              $scope.formData2 = {id:json.projectDTO.id};
              for (k in $scope.formData){
                $scope.formData2[k] = $scope.formData[k].join(",");
              }
              productService.productProfitUpdate($scope.formData2).then(function(json){
                if (json.statusCode){
                  alert("保存年化及佣金时，出错了:" + json.statusCode);
                }
              });
            }
            
            if($scope.attachs.length > 0){
              // 保存附件的数据
              $scope.formDataAttach = {fName:[],fileUrl:[],fileType:[]};
              angular.forEach($scope.attachs,function(o,i){
                if (o['fName'] && o['fPath'] && o['fType']){
                  $scope.formDataAttach['fName'].push(o['fName']);
                  $scope.formDataAttach['fileUrl'].push(o['fPath']);
                  $scope.formDataAttach['fileType'].push(o['fType']);
                }
              });
              $scope.formData2Attach = {pId:json.projectDTO.id};
              for (k in $scope.formDataAttach){
                $scope.formData2Attach[k] = $scope.formDataAttach[k].join(",");
              }
              productService.productAttachUpdate($scope.formData2Attach).then(function(json){
                if (json.statusCode){
                  alert("保存附件时，出错了:" + json.statusCode);
                }
              });
            }

            // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
            if($scope.ct && $scope.report.id){
              delete $scope.report.id;
              $scope.report.fpProductId = json.projectDTO.id;
              $scope.report.fpProductStatus = "2";
              reportService.deepAnalyticsSave($scope.report).then(function(json){
                if (json.statusCode){
                  alert("出错了:" + json.statusCode);
                }
              });
            }
          }
          $scope.alertNextPage("产品录入成功!");
          $location.path("/pevcproduct/edit").search({id:json.projectDTO.id,t:$scope.t});
        }
      });
    }else{
      if ($scope.product.pSummary == undefined || !$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };

  $scope.onUploadFile({
      showMessage : function(m){ alert(m); },
      onComplete:function(f,response,id){
        id--;
        if (response.statusCode == "0000") {
          if(id==0){
             $scope.product.pImageUri = response.attribute.fileUrl;
           }else if(id==1){
            $scope.product.peLogoUri= response.attribute.fileUrl;
           }else if(id==2){
            $scope.product.peHomeLogoUri= response.attribute.fileUrl;
           }
          $scope.$apply();
        } else { 
          alert('上传失败'); 
        }
      }    
  });
}]);


faApp.controller('PEVCProductBaseInfoCtrl',['$scope','productService','supplierService','$location','$controller','$routeParams','$filter','companyService','$route',function($scope,productService,supplierService,$location,$controller,$routeParams,$filter,companyService,$route) {   
  $controller('BaseCtrl', {$scope: $scope});

  $scope.product = {};
  $scope.loading = true; 
  $scope.pathText = "修改产品";
  $scope.id = $routeParams.id;
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"}); 
  $scope.companys = [];
  $scope.companysMap = {};

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });

  $scope.supplierListOfProduct = [];
  $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.allTjzls = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
      $scope.allTjzls[o] = true;  
    }); 
    }
    $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
    $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
    $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
    $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
    $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
    $scope.product.image = $scope.product.pImageUri;
    $scope.accessNameOfCompany = $scope.product.pAccessName;

    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
        $scope.allTjzls[o] = true;  
      }); 
    }
    if($scope.product.projectExpandDTO!=undefined){
      //PE/VC新增扩展字段
    $scope.product.peManageOrg=$scope.product.projectExpandDTO.peManageOrg;
    $scope.product.peOrganizeShape=$scope.product.projectExpandDTO.peOrganizeShape;
    $scope.product.peFundShape=$scope.product.projectExpandDTO.peFundShape;
    $scope.product.peSubscriptionFee=$scope.product.projectExpandDTO.peSubscriptionFee;
    $scope.product.peManagementExpense=$scope.product.projectExpandDTO.peManagementExpense;
    $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
    $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
    $scope.product.peRevenueSharing=$scope.product.projectExpandDTO.peRevenueSharing;
    $scope.product.peCompanyDescription=$scope.product.projectExpandDTO.peCompanyDescription;
    delete $scope.product.projectExpandDTO;
    }
    

    delete $scope.product.pSaleTimeStart;
    delete $scope.product.pSaleTimeEnd;
    delete $scope.product.pEstablishmentTime;
    delete $scope.product.pCode;

    $scope.t = $scope.product.pType;

    $scope.loading = false;
  });

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };
  
  $scope.save = function(){
    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;

      if ($scope.product.pSizeRatioType && ($scope.product.pSizeRatioExplain == undefined || $scope.product.pSizeRatioExplain == "")){
        $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
      }
      $scope.product.tjzls=$scope.selectTjzls.join(",");
      productService.productUpdatePEVC($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品修改成功!");
          $route.reload();
        }
      });
    }else{
      if (!$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };
 
  $scope.onUploadFile({
      showMessage : function(m){ alert(m); },
      onComplete:function(f,response,id){
        id--;
        if (response.statusCode == "0000") {
          if(id==0){
             $scope.product.pImageUri = response.attribute.fileUrl;
           }else if(id==1){
            $scope.product.peLogoUri= response.attribute.fileUrl;
           }else if(id==2){
            $scope.product.peHomeLogoUri= response.attribute.fileUrl;
           }
          $scope.$apply();
        } else { 
          alert('上传失败'); 
        }
      }    
  });

  $scope.selectInvestOwner = function(){
    $scope.product.pInvestOwner = $scope.product.pInvestOwnerId == undefined ? $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName'] : "";
  };
  
  $scope.changePsizeRatioType = function(){
    if ($scope.product.pSizeRatioType){
      $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
    }
  };
}]);


faApp.controller('PEVCProductEditCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','companyService','sessionService',function($scope,productService,$location,$controller,$routeParams,$filter,companyService,sessionService) {   
  $scope.id = $routeParams.id;
  $scope.t = $routeParams.t;
  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    viewUrl : "#/pevcproduct/view?id=" + $scope.id,
    baseUrl : "#/pevcproduct/baseInfo?id=" + $scope.id,
    saleprocessUrl: "#/pevcproduct/saleProcess?id=" + $scope.id,
    profitUrl : "#/product/profit?id=" + $scope.id,
    attachmentUrl : "#/product/attach?id=" + $scope.id,
    roadVideo : "#/product/video?id=" + $scope.id,
  };
  
  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };
  
  var lastProductTab = sessionService.getItem('lastProductTab') || 'viewUrl'; 
  $scope.changeTab('viewUrl');
  
  $scope.pathText = $scope.id ? "修改产品" : "新建产品"; 
  
  angular.element(document).ready(function(){
    // console.log(1);
    if ($(window).height() > 300) $scope.iframeHeight = $(window).height() - 130;
  });

}]);

faApp.controller('PEVCProductViewCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','userService','$route',function($scope,productService,$location,$controller,$routeParams,$filter,userService,$route) {   
  $controller('ProductBaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];

  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
    $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
    $scope.projectRabateList = json.projectRabateList; 
    console.log($scope.projectRabateList);
  });
  
  $scope.userList = [];
  userService.userList().then(function(json){
    $scope.userRawList = json.list || [];
    angular.forEach($scope.userRawList,function(o){
      if (o.userNickname != $scope.loginStatus.loginName){
        $scope.userList.push(o);
      }
    });
    
  });
  $scope.transList = [];
  productService.transPermissionList({pProjectId:$scope.id,pageSize:1000}).then(function(json){
    $scope.transList = json.list || [];
  });
  $scope.trans = {pProjectId:$scope.id};
  $scope.save = function(){
    if (!$scope.form.$invalid){
      productService.transPermissionAdd($scope.trans).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");
          parent.location.href = parent.location.href;
          //$route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
}]);

faApp.controller('PEVCProductSaleProcessCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.item = {id:$scope.id};
  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
   
    $scope.project = json.project;
    $scope.item.pAllSubscriptionAmountTmp = json.project.pAllSubscriptionAmount/10000;
    $scope.item.pIssuingScale = json.project.pIssuingScale / 10000;
    $scope.item.pRecruitmentSummary = json.project.pRecruitmentSummary;
    $scope.item.pSaleStatus = json.project.pSaleStatus;
    $scope.item.pAllSubscriptionNum = json.project.pAllSubscriptionNum?json.project.pAllSubscriptionNum:0;
    // $scope.item.pSizeRatioType = json.project.pSizeRatioType;
    // $scope.item.pSizeRatioExplain = json.project.pSizeRatioExplain;
     $scope.item.pPeriods = json.project.pPeriods;
      $scope.loading = false; 
  });

  $scope.changePsizeRatioType = function(){
    if ($scope.item.pSizeRatioType){
      $scope.item.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.item.pSizeRatioType);
    }
  };

  $scope.save = function(){
    if($scope.item.pAllSubscriptionAmountTmp > $scope.item.pIssuingScale){
      alert("已销售总额不能大于单期规模！");
      return;
    }
    if($scope.item.pIssuingScale > ($scope.project.pAllIssuingScale/10000)){
      alert("单期规模不能大于发行规模！");
      return;
    }
    $scope.item.pAllSubscriptionAmount = $scope.item.pAllSubscriptionAmountTmp * 10000;
    $scope.item.pIssuingScale = $scope.item.pIssuingScale * 10000;
    productService.updateSaleProcess($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        productService.updateRecruitmentProcess($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }  
        });
        
        productService.productEdit($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("产品修改成功!");
            $route.reload();
          }
        });
      }
    });
  };
}]);
faApp.controller('ProductBaseCtrl',['$scope','productService','$location','$controller','$route','$routeParams',function($scope,productService,$location,$controller,$route,$routeParams) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.deleteProduct = function(id){
    productService.productDelete(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品删除成功！");
        if ($scope.pageChanged){$route.reload();}
        else $location.path("/product/list");
      }
    });
  };

  $scope.stopProduct = function(id,status){
    productService.productStop(id,status).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品已下架！");
        $route.reload();
      }
    });
  };

  $scope.productPassVerify = function(id){
    productService.productPassVerify(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品审核通过！");
        $route.reload();
      }
    });
  };
  
//提交审核
  $scope.addProductCheckVerify = function(id,type){
    //addCheckType  1为新增产品审核   2为修改费用审核 
    productService.addProductCheckVerify({"id":id,"addCheckType":type}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品提交审核成功！");
        $route.reload();
      }
    });
  };

  $scope.productDenyVerify = function(id,type){
    productService.productDenyVerify(id,type).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品审核已拒绝！");
        $route.reload();
      }
    });
  };

  $scope.productPassPublish = function(id){
    productService.productPassPublish(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("产品发布成功！");
        $route.reload();
      }
    });
  };

  $scope.showProductEstablish = function(id){
    $scope.estabItem = $scope.estabItem || {};
    $scope.estabItem.id = id;
    $scope.showEstablishaFormFlag = true;
  };

  $scope.productEstablish = function(id){
    if (!$scope.estagForm.$invalid){
      $scope.estabItem.pEstablishmentTimeStr += " 00:00:00";
      productService.productEstablish($scope.estabItem).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品成立操作成功！");
          $route.reload();
        }
      });
    }else{
      alert("请先填写时间");
    }
  };
}]);

faApp.controller('ProductListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});

  $scope.ctrlName = "ProductListCtrl";
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.products = [];
  $scope.loading = true;
  //获取页面类型，信托、资管
  $scope.t = $routeParams.t;

  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  var hasPage = 'hasPageProductListCtrl';

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
  };

  $scope.$watch('config',function(newVal,oldVal,scope){
   
    //根据页面传入的信托、资管类型，添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    if($scope.config['pTypeList']==undefined||$scope.config['pTypeList']==''){
      $scope.config['pTypeList'] = "02,03";
    }
   if(newVal==oldVal)return;
    productService.productList($scope.config).then(function(json){
      $scope.products = json.projectList;
      $scope.pager = json.projectDTO;
      $scope.loading = false;
    });
  },true);

  $scope.searchMap['orderBy'] = $routeParams.orderBy || '',
    $scope.searchMap['orderByTag'] = $routeParams.orderByTag || '',
    $scope.config['orderBy'] = $routeParams.orderBy || '',
    $scope.config['orderByTag'] = $routeParams.orderByTag || '',

    $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }

    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.upDate = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
          pids += $(this).val() + ",";
        }
    });
     if(pids.length > 0){
      if(!confirm("确认更新吗?")){
        return;
      }
      pids = pids.substring(0, pids.length - 1);
      var product = {
        "ids":pids
      }
      //修改产品的更新时间
      productService.productEdit(product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功！");
          $route.reload();
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }


  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;
    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    !notsave && $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&t=' + $scope.t;
      $location.url(url);
    }
  }

  $scope.getLastSearchConfig();
  $scope.search();

}]);

faApp.controller('ProductQDListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.ctrlName = "ProductQDListCtrl";
  $controller('BaseListCtrl', {$scope: $scope});
  
  $scope.sortSelected="1";

  $scope.products = [];
  $scope.loading = true;

  $scope.showDataPreview = false;
  $scope.dataPreview=[];
  //当前预览哪个文件
  $scope.changeShowDataPreview =function(f,v){
    $scope.showDataPreview=f;
    if(v){
      $scope.dataPreview=v;
    }else{
      $scope.dataPreview=[];
    }
  }
  //获取页面类型，信托、资管   
  $scope.t = $routeParams.t;
  if(!$scope.t){//默认全部
    $scope.t="02,03,06,07";
  }

  //产品名字
  $scope.config.pShortName=$routeParams.name?$routeParams.name:"";
  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
        console.log(tmp);
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = "";
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
    console.log( $scope.config['pTypeList']);
  };
  $scope.changeProductTypeQuery = function(v){
    $scope.t = v;
    $scope.config['pTypeList'] = v;
    console.log( $scope.config['pTypeList']);
  };
    $scope.changeQueryType = function(v,t){
      var tmp = "";
      if(t!=true){
        $("[name="+v+"]").eq(0).removeAttr("checked");
      }
      $("[name="+v+"]").each(function(){
        if($(this).attr("checked") == "checked"){
          //t==true 为不限   清空所有条件和其他选中
          if($(this).val()==''&&t==true){
            temp="";
            $scope.config[v] = tmp;
            //循环清空复选框
            $("[name="+v+"]").removeAttr("checked");
            $("[name="+v+"]").eq(0).attr("checked","checked");
            return;
          }else{
            tmp += $(this).val() + ",";
            console.log(tmp);
          }
        }
      });
      if(tmp.length > 0){
        tmp = tmp.substring(0, tmp.length - 1);
      }else{
        //如果神马都没选，则还是显示默认页面类型
        tmp = "";
      }
      $scope.config[v] = tmp;
      console.log( $scope.config[v]);
    };
    $scope.changeProductSortBy = function(by){
      if(by){
        $scope.config.pageNo = 1;
        $scope.config.orderParameter = '';
        $scope.config.orderType = '';
        $scope.config.pRabateProfitParameter = '';
        $scope.config.pAnnualRevenueExpectParameter = '';
        if(by == '02'){
          $scope.config.pRabateProfitParameter = 'true';
        }else if(by == '03'){
          $scope.config.pAnnualRevenueExpectParameter = 'true';
        }else if(by == '04'){
          $scope.config.orderParameter = '01';
          $scope.config.orderType = '02';
        }else if(by == '05'){
          $scope.config.orderParameter = '03';
          $scope.config.orderType = '01';
        }
        $scope.productSort = by;
      }
    }
    //根据页面传入的信托、资管类型，添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    if($scope.config['pTypeList']==undefined||$scope.config['pTypeList']==''){
      $scope.config['pTypeList'] = "02,03,06,07";
    }
  $scope.$watch('config',function(){
    productService.productQDList($scope.config).then(function(json){
      $scope.products = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.searchMap['orderBy'] = 'id',
    $scope.searchMap['orderByTag'] = 'desc',
    $scope.config['orderBy'] = 'id',
    $scope.config['orderByTag'] = 'desc',

    $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }

    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
      });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }

}]);

faApp.controller('ProductQDViewCtrl',['$scope','$sce','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,$sce,productService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  productService.productQdQuery($scope.id).then(function(json){
    $scope.project = json.bean;
    $scope.project.summary=$sce.trustAsHtml($scope.project.summary);
  });

}]);

faApp.controller('ProductAddCtrl',['$scope', 'productService','reportService','$location','$controller','$timeout','companyService','supplierService','faService','$route','$filter','$routeParams',function($scope,productService,reportService,$location,$controller,$timeout,companyService,supplierService,faService,$route,$filter,$routeParams) {
  $controller('BaseCtrl', {$scope: $scope});


  $scope.product = {pMinimumAmountTmp:100,pRealSubscriptionAmount:0,pRealSubscriptionShare:0,pType:"02",pInvestType:"01",pPublicArea:"00",pSaleStatus:"03",pPaymentInterestType:"03",pEndEarlyIdentification:"0",pProgressiveAmountTmp:10,fpCorpId:0,fpProjectCorpType:'02',flagRaised:true};

    $scope.showXcxsearchnoRecord = false;

    $scope.pLabelItem = {};
    $scope.proserieslist = [];

  $scope.loading = true;
  $scope.pathText = "新增产品";
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};
  $scope.pid = $routeParams.id;

  $scope.supplierListOfProduct = [];
  $scope.accessNameOfCompany = "";

  $scope.t = $routeParams.t;
  $scope.outproduct={};
  if($routeParams.outProductId!=undefined){
    $scope.product.outProductId=$routeParams.outProductId;
  }
  if($routeParams.productName!=undefined){
    $scope.product.pName=$routeParams.productName;
    $scope.product.pFullName=$routeParams.productName;
  }

  //默认能竞价
  $scope.product.flagBidding=false;


  // 复制产品时，是否同时复制产品解析报告
  $scope.ct = $routeParams.ct;

  // 复制年化及佣金的数据
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.attachs = [];

  // 复制产品解析报告
  $scope.report = {};

  $scope.allTjzls = {};

    $scope.openSerarnoWin = function () {
        productService.xcxSearchNoRecordList().then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.showXcxsearchnoRecord = true;
                $scope.searchnolist = json.list;
            }
        });

    }
    $scope.getXcxsearchNoRecord = function (d) {
      console.info(d)
        $scope.product.pXcxSerarnoKeyword = d.keyword;

        $scope.showXcxsearchnoRecord = false;
    }

  if($scope.pid != undefined && $scope.pid.length > 0){
    //如果有值，则说明是点了复制按钮，则根据ID加载产品
    productService.productQuery($scope.pid).then(function(json){
      $scope.product = json.project;
      $scope.product.pLinkCode = $scope.product.pCode;
      $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
      $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
      $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
      $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
      $scope.product.pRaiseTime = $filter("date")($scope.product.pRaiseTime,"yyyy-MM-dd");

      $scope.product.pLetterTime = $filter("date")($scope.product.pLetterTime,"yyyy-MM-dd");
      $scope.product.pNoticeTime = $filter("date")($scope.product.pNoticeTime,"yyyy-MM-dd");
      if(json.project.pLabel) {
          var pLabelArr = json.project.pLabel.split(",");
          for(var i =0; i<pLabelArr.length; i++) {
              if (pLabelArr[i] == '23') {
                  $scope.pLabelItem.pLabel23 = '23'
              }
              if (pLabelArr[i] == '1') {
                  $scope.pLabelItem.pLabel1 = '1'
              }
              if (pLabelArr[i] == '2') {
                  $scope.pLabelItem.pLabel2 = '2'
              }
              if (pLabelArr[i] == '3') {
                  $scope.pLabelItem.pLabel3 = '3'
              }
              if (pLabelArr[i] == '4') {
                  $scope.pLabelItem.pLabel4 = '4'
              }
              if (pLabelArr[i] == '5') {
                  $scope.pLabelItem.pLabel5 = '5'
              }
              if (pLabelArr[i] == '6') {
                  $scope.pLabelItem.pLabel6 = '6'
              }
              if (pLabelArr[i] == '7') {
                  $scope.pLabelItem.pLabel7 = '7'
              }
              if (pLabelArr[i] == '8') {
                  $scope.pLabelItem.pLabel8 = '8'
              }
              if (pLabelArr[i] == '9') {
                  $scope.pLabelItem.pLabel9 = '9'
              }
              if (pLabelArr[i] == '10') {
                  $scope.pLabelItem.pLabel10 = '10'
              }
              if (pLabelArr[i] == '11') {
                  $scope.pLabelItem.pLabel11 = '11'
              }
              if (pLabelArr[i] == '12') {
                  $scope.pLabelItem.pLabel12 = '12'
              }
              if (pLabelArr[i] == '13') {
                  $scope.pLabelItem.pLabel13 = '13'
              }
              if (pLabelArr[i] == '14') {
                  $scope.pLabelItem.pLabel14 = '14'
              }
              if (pLabelArr[i] == '15') {
                  $scope.pLabelItem.pLabel15 = '15'
              }
              if (pLabelArr[i] == '16') {
                  $scope.pLabelItem.pLabel16 = '16'
              }
              if (pLabelArr[i] == '17') {
                  $scope.pLabelItem.pLabel17 = '17'
              }
              if (pLabelArr[i] == '18') {
                  $scope.pLabelItem.pLabel18 = '18'
              }
              if (pLabelArr[i] == '19') {
                  $scope.pLabelItem.pLabel19 = '19'
              }
              if (pLabelArr[i] == '22') {
                  $scope.pLabelItem.pLabel22 = '22'
              }
          }
      }

      $scope.proserieslist = json.fpProjectSeriesList;

      $scope.product.image = $scope.product.pImageUri;
      $scope.product.fpCorpId = "0";
      $scope.product.fpProjectCorpType = "02";
      if($scope.product.tjzls!=undefined){
        angular.forEach($scope.product.tjzls.split(","),function(o){
          $scope.allTjzls[o] = true;
        });
      }
      // 复制年化及佣金的数据
      $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
      $scope.projectRabateList = json.projectRabateList;


      if($scope.product.projectExpandDTO!=undefined){
        $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
        $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
        delete $scope.product.projectExpandDTO;
      }

      delete $scope.product.pSaleTimeStart;
      delete $scope.product.pSaleTimeEnd;
      delete $scope.product.pEstablishmentTime;
      delete $scope.product.pCode;

      $scope.product.pRealSubscriptionAmount = 0;
      $scope.product.pRealSubscriptionShare = 0;
      //delete $scope.product.pRealSubscriptionAmount;
      //delete $scope.product.pRealSubscriptionShare;
    });

    // 加载原产品附件的数据
    productService.productAttachList($scope.pid).then(function(json){
      $scope.attachs = json.projectAttachmentsList;
    });

    // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
    if($scope.ct){
      reportService.deepAnalyticsDetail($scope.pid).then(function(json){
        if(json.dto){
          $scope.report = json.dto || {};
          delete $scope.report.fpProductId;
          delete $scope.report.fpProductStatus;
          // delete $scope.report.id;
        }
      });
    }
  } else {
      productService.proSeriesList().then(function(json){
          $scope.proserieslist = json.fpProjectSeriesList;
      })
  }

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });
    $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.product.pSummary = "<div style='width:1000px;'><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='mjzh'></a>募集账号</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='bcsm'></a>补充说明</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='cpys'></a>产品优势</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='fxkz'></a>风险控制</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='hkly'></a>还款来源</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='zjyt'></a>资金用途</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='rzf'></a>融资方</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='dbf'></a>担保方</li><li style=''>---输入内容---</li></ul></div>";

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    var pLabel="";
    if($scope.pLabelItem.pLabel23 && $scope.pLabelItem.pLabel23=='0') {
        pLabel+="23,";
    }
    if($scope.pLabelItem.pLabel1 && $scope.pLabelItem.pLabel1=='1') {
        pLabel+="1,";
    }
    if($scope.pLabelItem.pLabel2 && $scope.pLabelItem.pLabel2=='2') {
        pLabel+="2,";
    }
    if($scope.pLabelItem.pLabel3 && $scope.pLabelItem.pLabel3=='3') {
        pLabel+="3,";
    }
    if($scope.pLabelItem.pLabel4 && $scope.pLabelItem.pLabel4=='4') {
        pLabel+="4,";
    }
    if($scope.pLabelItem.pLabel5 && $scope.pLabelItem.pLabel5=='5') {
        pLabel+="5,";
    }
    if($scope.pLabelItem.pLabel6 && $scope.pLabelItem.pLabel6=='6') {
        pLabel+="6,";
    }
    if($scope.pLabelItem.pLabel7 && $scope.pLabelItem.pLabel7=='7') {
        pLabel+="7,";
    }
    if($scope.pLabelItem.pLabel8 && $scope.pLabelItem.pLabel8=='8') {
        pLabel+="8,";
    }
    if($scope.pLabelItem.pLabel9 && $scope.pLabelItem.pLabel9=='9') {
        pLabel+="9,";
    }
    if($scope.pLabelItem.pLabel10 && $scope.pLabelItem.pLabel10=='10') {
        pLabel+="10,";
    }
    if($scope.pLabelItem.pLabel11 && $scope.pLabelItem.pLabel11=='11') {
        pLabel+="11,";
    }
    if($scope.pLabelItem.pLabel12 && $scope.pLabelItem.pLabel12=='12') {
        pLabel+="12,";
    }
    if($scope.pLabelItem.pLabel13 && $scope.pLabelItem.pLabel13=='13') {
        pLabel+="13,";
    }
    if($scope.pLabelItem.pLabel14 && $scope.pLabelItem.pLabel14=='14') {
        pLabel+="14,";
    }
    if($scope.pLabelItem.pLabel15 && $scope.pLabelItem.pLabel15=='15') {
        pLabel+="15,";
    }
    if($scope.pLabelItem.pLabel16 && $scope.pLabelItem.pLabel16=='16') {
        pLabel+="16,";
    }
    if($scope.pLabelItem.pLabel17 && $scope.pLabelItem.pLabel17=='17') {
        pLabel+="17,";
    }
      if($scope.pLabelItem.pLabel18 && $scope.pLabelItem.pLabel18=='18') {
          pLabel+="18,";
      }
      if($scope.pLabelItem.pLabel19 && $scope.pLabelItem.pLabel19=='19') {
          pLabel+="19";
      }
      if($scope.pLabelItem.pLabel22 && $scope.pLabelItem.pLabel22=='22') {
          pLabel+="22";
      }

    console.info("产品标签:"+pLabel)
    if(pLabel && pLabel.substr(pLabel.length-1,1).indexOf(",")>-1) {
        pLabel = pLabel.substr(0, pLabel.length-1);
    }
    $scope.product.pLabel = pLabel;

    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
          flag = true;
          $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.id = "";
      $scope.product.pType = $scope.t;
      //$scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pIssuingScale = 0;

      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      if($scope.t != undefined && $scope.t == "02"){
        $scope.product.pInvestOwnerId && ($scope.product.pInvestOwner = $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName']);
      }
      $scope.product.pInvestOwnerId = $scope.product.pInvestOwnerId || -1;
      if($scope.product.pInvestOwnerId == -1 && $scope.t == "02"){
        $scope.product.pInvestOwner = "";
      }

      if($scope.ct && $scope.report.id){
        $scope.product.copyType = "01";
      }

      $scope.product.tjzls=$scope.selectTjzls.join(",");

      productService.productAdd($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
          if($scope.product.pAllIssuingScale>10000){
            $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
          }
        }else{

          //产品录入成功之后，如果是复制操作则把年化佣金、附件同时保存到数据库。
          if($scope.pid != undefined && $scope.pid.length > 0){
            if($scope.projectAnnualRevenue.length > 0 && $scope.projectRabateList.length > 0){
              $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pBackRabateProfit:[],pCoreBackPrice:[],pCostBackPrice:[],pBackSellingPrice:[]};
              angular.forEach($scope.projectAnnualRevenue,function(o,i){
                //产品ID
                $scope.formData['pId'].push(json.projectDTO.id);
                //返佣类型，01：百分比
                $scope.formData['pRebateType'].push("01");
                //起始金额
                $scope.formData['pStartAmount'].push(o['pStartAmount']);
                // 结束金额
                $scope.formData['pEndAmount'].push(o['pEndAmount']);
                // 预期年化率
                $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
                // 返佣率
                $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
                // 核心价
                $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
                // 成本价
                $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
                // 机构价
                $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);

                // 后端挂网价
                $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);
                // 后端核心价
                $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
                // 后端成本价
                $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
                // 后端机构价
                $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);




                // 是否协议
                $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
              });
              $scope.formData2 = {id:json.projectDTO.id};
              for (k in $scope.formData){
                $scope.formData2[k] = $scope.formData[k].join(",");
              }
              productService.productProfitUpdate($scope.formData2).then(function(json){
                if (json.statusCode){
                  alert("保存年化及佣金时，出错了:" + json.statusCode);
                }
              });
            }

            if($scope.attachs.length > 0){
              // 保存附件的数据
              $scope.formDataAttach = {fName:[],fileUrl:[],fileType:[]};
              angular.forEach($scope.attachs,function(o,i){
                if (o['fName'] && o['fPath'] && o['fType']){
                  $scope.formDataAttach['fName'].push(o['fName']);
                  $scope.formDataAttach['fileUrl'].push(o['fPath']);
                  $scope.formDataAttach['fileType'].push(o['fType']);
                }
              });
              $scope.formData2Attach = {pId:json.projectDTO.id};
              for (k in $scope.formDataAttach){
                $scope.formData2Attach[k] = $scope.formDataAttach[k].join(",");
              }
              productService.productAttachUpdate($scope.formData2Attach).then(function(json){
                if (json.statusCode){
                  alert("保存附件时，出错了:" + json.statusCode);
                }
              });
            }

            // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
            if($scope.ct && $scope.report.id){
              delete $scope.report.id;
              $scope.report.fpProductId = json.projectDTO.id;
              $scope.report.fpProductStatus = "2";
              reportService.deepAnalyticsSave($scope.report).then(function(json){
                if (json.statusCode){
                  alert("出错了:" + json.statusCode);
                }
              });
            }
          }
          $scope.alertNextPage("产品录入成功!");
          $location.path("/product/edit").search({id:json.projectDTO.id,t:$scope.t});
        }
      });
    }else{
      if ($scope.product.pSummary == undefined || !$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };
//  $scope.onUploadFile({
//    showMessage : function(m){ alert(m); },
  //   onComplete:function(f,response){
  //     if (response.statusCode == "0000") {
//        $scope.product.image = response.attribute.fileUrl;
//        $scope.$apply();
//      } else {
  //       alert('上传失败');
  //     }
  //   }
  // });
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        if(id==0){
          $scope.product.image = response.attribute.fileUrl;
        }else if(id==1){
          $scope.product.peLogoUri= response.attribute.fileUrl;
        }else if(id==2){
          $scope.product.peHomeLogoUri= response.attribute.fileUrl;
        }
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);

faApp.controller('ProSeriesCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
  $scope.proSeriesItem = {}
  $scope.proSeriesSave = function () {
    if(!$scope.myform.$invalid) {
        productService.proSeriesAdd($scope.proSeriesItem).then(function(json){
            console.info("新增产品系列")
          if(json.statusCode == '2003') {
              alert("产品系列已存在!")
          } else {
              $scope.proserieslist.unshift($scope.proSeriesItem);

              alert("产品系列新增成功!");
              $scope.$parent.showProSeriesFlag = false;

              $scope.proSeriesItem = {}
          }
        })
    }
  }

    $scope.proSeriesDelete = function (d, $index) {
        productService.proSeriesDelete(d).then(function(json){
            console.info("新增产品系列")
            if(json.statusCode == '2002') {
                alert("参数缺失!")
            } else if(json.statusCode == '5001'){
                alert("数据已被引用，不可删除!")
            } else {
                alert("删除成功!");
                $scope.proserieslist.splice($index, 1)
                if($scope.product.pSeries==d.proSeriesName) {
                    $scope.product.pSeries = '';
                }
            }


        })
    }
}]);

faApp.controller('ProductEditCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','companyService','sessionService',function($scope,productService,$location,$controller,$routeParams,$filter,companyService,sessionService) {

  $scope.id = $routeParams.id;
  $scope.t = $routeParams.t;
  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    viewUrl : "#/product/view?id=" + $scope.id,
    baseUrl : "#/product/base?id=" + $scope.id,
    saleprocessUrl: "#/product/saleProcess?id=" + $scope.id,
    profitUrl : "#/product/profit?id=" + $scope.id,
    attachmentUrl : "#/product/attach?id=" + $scope.id,
    roadVideo : "#/product/video?id=" + $scope.id
  };

  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };

  var lastProductTab = sessionService.getItem('lastProductTab') || 'viewUrl';
  $scope.changeTab('viewUrl');

  $scope.pathText = $scope.id ? "修改产品" : "新建产品";

  angular.element(document).ready(function(){
    // console.log(1);
    if ($(window).height() > 300) $scope.iframeHeight = $(window).height() - 130;
  });
}]);

faApp.controller('ProductBaseInfoCtrl',['$scope','productService','supplierService','$location','$controller','$routeParams','$filter','companyService','$route',function($scope,productService,supplierService,$location,$controller,$routeParams,$filter,companyService,$route) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.product = {};
  $scope.pLabelItem = {}
    $scope.proserieslist = [];

  $scope.showProSeriesFlag = false;
  $scope.showXcxsearchnoRecord = false;

  $scope.loading = true;
  $scope.pathText = "修改产品";
  $scope.id = $routeParams.id;
    $scope.tabUrlMap = {
        pronotice: "#/product/pronoticeattach?id=" + $routeParams.id
    };
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });

  $scope.supplierListOfProduct = [];
 
  $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.allTjzls = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    $scope.t = $scope.product.pType;
    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
        $scope.allTjzls[o] = true;
      });
    }
    console.log($scope.allTjzls);

    $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
    $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
    $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
    $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
    $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
    $scope.product.pRaiseTime = $filter("date")($scope.product.pRaiseTime,"yyyy-MM-dd");
    $scope.product.pLetterTime = $filter("date")($scope.product.pLetterTime,"yyyy-MM-dd");
    $scope.product.pNoticeTime = $filter("date")($scope.product.pNoticeTime,"yyyy-MM-dd");

    $scope.proserieslist = json.fpProjectSeriesList;
    if(json.project.pLabel) {
        var pLabelArr = json.project.pLabel.split(",");
        for(var i =0; i<pLabelArr.length; i++) {
            if (pLabelArr[i] == '23') {
                $scope.pLabelItem.pLabel23 = '23'
            }
            if (pLabelArr[i] == '1') {
                $scope.pLabelItem.pLabel1 = '1'
            }
            if (pLabelArr[i] == '2') {
                $scope.pLabelItem.pLabel2 = '2'
            }
            if (pLabelArr[i] == '3') {
                $scope.pLabelItem.pLabel3 = '3'
            }
            if (pLabelArr[i] == '4') {
                $scope.pLabelItem.pLabel4 = '4'
            }
            if (pLabelArr[i] == '5') {
                $scope.pLabelItem.pLabel5 = '5'
            }
            if (pLabelArr[i] == '6') {
                $scope.pLabelItem.pLabel6 = '6'
            }
            if (pLabelArr[i] == '7') {
                $scope.pLabelItem.pLabel7 = '7'
            }
            if (pLabelArr[i] == '8') {
                $scope.pLabelItem.pLabel8 = '8'
            }
            if (pLabelArr[i] == '9') {
                $scope.pLabelItem.pLabel9 = '9'
            }
            if (pLabelArr[i] == '10') {
                $scope.pLabelItem.pLabel10 = '10'
            }
            if (pLabelArr[i] == '11') {
                $scope.pLabelItem.pLabel11 = '11'
            }
            if (pLabelArr[i] == '12') {
                $scope.pLabelItem.pLabel12 = '12'
            }
            if (pLabelArr[i] == '13') {
                $scope.pLabelItem.pLabel13 = '13'
            }
            if (pLabelArr[i] == '14') {
                $scope.pLabelItem.pLabel14 = '14'
            }
            if (pLabelArr[i] == '15') {
                $scope.pLabelItem.pLabel15 = '15'
            }
            if (pLabelArr[i] == '16') {
                $scope.pLabelItem.pLabel16 = '16'
            }
            if (pLabelArr[i] == '17') {
                $scope.pLabelItem.pLabel17 = '17'
            }
            if (pLabelArr[i] == '18') {
                $scope.pLabelItem.pLabel18 = '18'
            }
            if (pLabelArr[i] == '19') {
                $scope.pLabelItem.pLabel19 = '19'
            }
            if (pLabelArr[i] == '22') {
                $scope.pLabelItem.pLabel22 = '22'
            }
        }
      }

    $scope.product.image = $scope.product.pImageUri;
    $scope.accessNameOfCompany = $scope.product.pAccessName;


    if($scope.product.projectExpandDTO!=undefined){
      $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
      $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
      delete $scope.product.projectExpandDTO;
    }


    delete $scope.product.pSaleTimeStart;
    delete $scope.product.pSaleTimeEnd;
    delete $scope.product.pEstablishmentTime;
    delete $scope.product.pCode;



    $scope.t = $scope.product.pType;


    $scope.loading = false;
  });

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){

        var pLabel="";
        if($scope.pLabelItem.pLabel23 && $scope.pLabelItem.pLabel23=='23') {
            pLabel+="23,";
        }
        if($scope.pLabelItem.pLabel1 && $scope.pLabelItem.pLabel1=='1') {
            pLabel+="1,";
        }
        if($scope.pLabelItem.pLabel2 && $scope.pLabelItem.pLabel2=='2') {
            pLabel+="2,";
        }
        if($scope.pLabelItem.pLabel3 && $scope.pLabelItem.pLabel3=='3') {
            pLabel+="3,";
        }
        if($scope.pLabelItem.pLabel4 && $scope.pLabelItem.pLabel4=='4') {
            pLabel+="4,";
        }
        if($scope.pLabelItem.pLabel5 && $scope.pLabelItem.pLabel5=='5') {
            pLabel+="5,";
        }
        if($scope.pLabelItem.pLabel6 && $scope.pLabelItem.pLabel6=='6') {
            pLabel+="6,";
        }
        if($scope.pLabelItem.pLabel7 && $scope.pLabelItem.pLabel7=='7') {
            pLabel+="7,";
        }
        if($scope.pLabelItem.pLabel8 && $scope.pLabelItem.pLabel8=='8') {
            pLabel+="8,";
        }
        if($scope.pLabelItem.pLabel9 && $scope.pLabelItem.pLabel9=='9') {
            pLabel+="9,";
        }
        if($scope.pLabelItem.pLabel10 && $scope.pLabelItem.pLabel10=='10') {
            pLabel+="10,";
        }
        if($scope.pLabelItem.pLabel11 && $scope.pLabelItem.pLabel11=='11') {
            pLabel+="11,";
        }
        if($scope.pLabelItem.pLabel12 && $scope.pLabelItem.pLabel12=='12') {
            pLabel+="12,";
        }
        if($scope.pLabelItem.pLabel13 && $scope.pLabelItem.pLabel13=='13') {
            pLabel+="13,";
        }
        if($scope.pLabelItem.pLabel14 && $scope.pLabelItem.pLabel14=='14') {
            pLabel+="14,";
        }
        if($scope.pLabelItem.pLabel15 && $scope.pLabelItem.pLabel15=='15') {
            pLabel+="15,";
        }
        if($scope.pLabelItem.pLabel16 && $scope.pLabelItem.pLabel16=='16') {
            pLabel+="16,";
        }
        if($scope.pLabelItem.pLabel17 && $scope.pLabelItem.pLabel17=='17') {
            pLabel+="17,";
        }
        if($scope.pLabelItem.pLabel18 && $scope.pLabelItem.pLabel18=='18') {
            pLabel+="18,";
        }
        if($scope.pLabelItem.pLabel19 && $scope.pLabelItem.pLabel19=='19') {
            pLabel+="19";
        }
        if($scope.pLabelItem.pLabel22 && $scope.pLabelItem.pLabel22=='22') {
            pLabel+="22";
        }

        console.info("产品标签:"+pLabel)
        if(pLabel && pLabel.substr(pLabel.length-1,1).indexOf(",")>-1) {
            pLabel = pLabel.substr(0, pLabel.length-1);
        }
        $scope.product.pLabel = pLabel;

      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
          flag = true;
          $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      if($scope.t != undefined && $scope.t == "02"){
        $scope.product.pInvestOwnerId && ($scope.product.pInvestOwner = $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName']);
      }
      $scope.product.pInvestOwnerId = $scope.product.pInvestOwnerId || -1;
      if($scope.product.pInvestOwnerId == -1 && $scope.t == "02"){
        $scope.product.pInvestOwner = "";
      }

      if ($scope.product.pSizeRatioType && ($scope.product.pSizeRatioExplain == undefined || $scope.product.pSizeRatioExplain == "")){
        $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
      }

      $scope.product.tjzls=$scope.selectTjzls.join(",");

      productService.productEdit($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品修改成功!");
          //$location.path("/product/list").search({orderBy:"updateDate",orderByTag:"desc"});
          $route.reload();
        }
      });
    }else{
      if (!$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };

  $scope.openSerarnoWin = function () {
      productService.xcxSearchNoRecordList().then(function (json) {

          if (json.statusCode) {
              alert("出错了:" + json.statusCode);
          } else {
              $scope.showXcxsearchnoRecord = true;
              $scope.searchnolist = json.list;
          }
      });
  }
    $scope.getXcxsearchNoRecord = function (d) {
        $scope.product.pXcxSerarnoKeyword = d.keyword;

        $scope.showXcxsearchnoRecord = false;
    }

  // $scope.onUploadFile({
  //   showMessage : function(m){ alert(m); },
  //   onComplete:function(f,response){
  //     if (response.statusCode == "0000") {
  //       $scope.product.image = response.attribute.fileUrl;
  //       $scope.$apply();
  //     } else {
  //       alert('上传失败');
  //     }
  //   }
  // });
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response,id){
      id--;
      if (response.statusCode == "0000") {
        if(id==0){
          $scope.product.image = response.attribute.fileUrl;
        }else if(id==1){
          $scope.product.peLogoUri= response.attribute.fileUrl;
        }else if(id==2){
          $scope.product.peHomeLogoUri= response.attribute.fileUrl;
        }
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

  $scope.selectInvestOwner = function(){
    $scope.product.pInvestOwner = $scope.product.pInvestOwnerId == undefined ? $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName'] : "";
  };

  $scope.changePsizeRatioType = function(){
    if ($scope.product.pSizeRatioType){
      $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
    }
  };
}]);

faApp.controller('ProductViewCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','userService','$route',function($scope,productService,$location,$controller,$routeParams,$filter,userService,$route) {
  $controller('ProductBaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.packPrice={};
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
    $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
    $scope.projectRabateList = json.projectRabateList;
    if($scope.loginStatus.loginName=='admin'){
      $scope.packPrice.packPriceFlag=true;
   
    }else{
      $scope.packPrice.packPriceFlag= json.packPriceFlag;
    }
  });

  $scope.userList = [];
  userService.userList().then(function(json){
    $scope.userRawList = json.list || [];
    angular.forEach($scope.userRawList,function(o){
      if (o.userNickname != $scope.loginStatus.loginName){
        $scope.userList.push(o);
      }
    });

  });

  $scope.transList = [];
  productService.transPermissionList({pProjectId:$scope.id,pageSize:1000}).then(function(json){
    $scope.transList = json.list || [];
  });

  $scope.trans = {pProjectId:$scope.id};
  $scope.save = function(){
    if (!$scope.form.$invalid){
      productService.transPermissionAdd($scope.trans).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");
          parent.location.href = parent.location.href;
          //$route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }

  };

}]);

faApp.controller('ProductSaleProcessCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,$location,$controller,$routeParams,$filter,$route) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {id:$scope.id};

  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
    $scope.loading = false;
    $scope.project = json.project;
    $scope.item.pAllSubscriptionNum = json.project.pAllSubscriptionNum;
    $scope.item.pAllSubscriptionAmountTmp = json.project.pAllSubscriptionAmount/10000;
    $scope.item.pRecruitmentSummary = json.project.pRecruitmentSummary;
    $scope.item.pSaleStatus = json.project.pSaleStatus;
    $scope.item.pSizeRatioType = json.project.pSizeRatioType;
    $scope.item.pSizeRatioExplain = json.project.pSizeRatioExplain;
    $scope.item.pIssuingScale = json.project.pIssuingScale / 10000;
    $scope.item.pPeriods = json.project.pPeriods;
  });

  $scope.changePsizeRatioType = function(){
    if ($scope.item.pSizeRatioType){
      $scope.item.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.item.pSizeRatioType);
    }
  };

  $scope.save = function(){
    if($scope.item.pAllSubscriptionAmountTmp > $scope.item.pIssuingScale){
      alert("已销售总额不能大于单期规模！");
      return;
    }
    if($scope.item.pIssuingScale > ($scope.project.pAllIssuingScale/10000)){
      alert("单期规模不能大于发行规模！");
      return;
    }
    $scope.item.pAllSubscriptionAmount = $scope.item.pAllSubscriptionAmountTmp * 10000;
    $scope.item.pIssuingScale = $scope.item.pIssuingScale * 10000;
    productService.updateSaleProcess($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        productService.updateRecruitmentProcess($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }
        });

        productService.productEdit($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("产品修改成功!");
            $route.reload();
          }
        });
      }
    });
  };
}]);

faApp.controller('ProductProfitCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$timeout',function($scope,productService,$location,$controller,$routeParams,$filter,$timeout) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.item['pIsAgreement'] = 0;
  $scope.loading = true;
  $scope.project = {};
  $scope.packPrice = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
  });
  productService.productProfitList($scope.id).then(function(json){
    $scope.loading = false;
    $scope.projectAnnualRevenue = json.projectAnnualRevenue;
    $scope.projectRabateList = json.projectRabateList;

    if($scope.loginStatus.loginName=='admin'){
      $scope.packPrice.packPriceFlag=true;
   
    }else{
      $scope.packPrice.packPriceFlag= json.packPriceFlag;
    }
  });
  function queryEditLog(){
      productService.productProfitLogList($scope.id).then(function(json){
        $scope.loading = false;
        $scope.logList = json.logList;
      });
  }
  queryEditLog();
  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item['pIsAgreement'] = $scope.projectRabateList[v]['pIsAgreement'];
    $scope.item['pStartAmount'] = $scope.projectAnnualRevenue[v]['pStartAmount'] / 10000;
    $scope.item['pEndAmount'] = $scope.projectAnnualRevenue[v]['pEndAmount'] / 10000;
    $scope.item['pAnnualRevenueExpect'] = $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'];
    $scope.item['pRabateProfit'] = $scope.projectRabateList[v]['pRabateProfit'];
    $scope.item['pCorePrice'] = $scope.projectRabateList[v]['pCorePrice'];
    $scope.item['pCostPrice'] = $scope.projectRabateList[v]['pCostPrice'];
    $scope.item['pSellingPrice'] = $scope.projectRabateList[v]['pSellingPrice'];
    $scope.item['pCostBackPrice'] = $scope.projectRabateList[v]['pCostBackPrice'];
    $scope.item['pCoreBackPrice'] = $scope.projectRabateList[v]['pCoreBackPrice'];
    $scope.item['pBackSellingPrice'] = $scope.projectRabateList[v]['pBackSellingPrice'];
    $scope.item['pBackRabateProfit'] = $scope.projectRabateList[v]['pBackRabateProfit'];
  };

  $scope.deleteItem = function(v){
    if ($scope.projectRabateList.length <= 1){
      alert("最后一个不能删除");
      return;
    }

    $scope.projectAnnualRevenue.splice(v,1);
    $scope.projectRabateList.splice(v,1);
    if (v > $scope.itemIndex){
      $scope.itemIndex --;
    }

    $scope.edit(0);
    $timeout(function(){
      $scope.save();
    },10);
  };

  $scope.changePrice = function(v){
      if(v==1){
        $scope.item.pCostPrice =$scope.item.pCorePrice;
        $scope.item.pSellingPrice =$scope.item.pCorePrice;
        $scope.item.pRabateProfit =$scope.item.pCorePrice;
      }else if(v==2){
        $scope.item.pCostBackPrice =$scope.item.pCoreBackPrice;
        $scope.item.pBackSellingPrice =$scope.item.pCoreBackPrice;
        $scope.item.pBackRabateProfit =$scope.item.pCoreBackPrice;
      }
  };

  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请填写完整信息！");
      return;
    }
    var v = $scope.itemIndex;
    if (v == undefined){
      if ($scope.projectRabateList.length < 1){
        v = 0;
      }else{
        v = $scope.projectAnnualRevenue.length;
      }
      $scope.projectRabateList[v] = {};
      $scope.projectAnnualRevenue[v] = {pId:$scope.id};
    }

    // $scope.projectRabateList[v]['pRabateProfit'] = $scope.item['pRabateProfit'];
    // $scope.projectRabateList[v]['pCorePrice'] = $scope.item['pCorePrice'];
    // $scope.projectRabateList[v]['pCostPrice'] = $scope.item['pCostPrice'];
    // $scope.projectRabateList[v]['pSellingPrice'] = $scope.item['pSellingPrice'];
    // $scope.projectRabateList[v]['pCostBackPrice']=$scope.item['pCostBackPrice'];
    // $scope.projectRabateList[v]['pCoreBackPrice']=$scope.item['pCoreBackPrice'];
    // $scope.projectRabateList[v]['pBackSellingPrice']=$scope.item['pBackSellingPrice'];
    // $scope.projectRabateList[v]['pBackRabateProfit']=$scope.item['pBackRabateProfit'];

    // $scope.projectAnnualRevenue[v]['pStartAmount'] = $scope.item['pStartAmount'] * 10000;
    // $scope.projectAnnualRevenue[v]['pEndAmount'] = $scope.item['pEndAmount'] ? ($scope.item['pEndAmount'] * 10000 ) : $scope.project.pIssuingScale;
    // $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'] = $scope.item['pAnnualRevenueExpect'];
    // $scope.projectRabateList[v]['pIsAgreement'] = $scope.item['pIsAgreement'] || 0;

    $scope.projectRabateList[v]['pIsAgreement'] = $scope.item['pIsAgreement'] || 0;
    $scope.projectAnnualRevenue[v]['pStartAmount'] = $scope.item['pStartAmount'] * 10000;
    $scope.projectAnnualRevenue[v]['pEndAmount'] = $scope.item['pEndAmount'] ? ($scope.item['pEndAmount'] * 10000 ) : $scope.project.pIssuingScale;
    $scope.projectAnnualRevenue[v]['pAnnualRevenueExpect'] = $scope.item['pAnnualRevenueExpect'];
    // 如果是协议价   把挂网价等价格 置为0
    if($scope.projectRabateList[v]['pIsAgreement']==1){
      $scope.projectRabateList[v]['pRabateProfit']=0;
      $scope.projectRabateList[v]['pCorePrice']=0;
      $scope.projectRabateList[v]['pCostPrice']=0;
      $scope.projectRabateList[v]['pSellingPrice']=0;
      $scope.projectRabateList[v]['pCostBackPrice']=0;
      $scope.projectRabateList[v]['pCoreBackPrice']=0;
      $scope.projectRabateList[v]['pBackSellingPrice']=0;
      $scope.projectRabateList[v]['pBackRabateProfit']=0;
    }else{
      $scope.projectRabateList[v]['pRabateProfit'] = $scope.item['pRabateProfit'];
      $scope.projectRabateList[v]['pCorePrice'] = $scope.item['pCorePrice'];
      $scope.projectRabateList[v]['pCostPrice'] = $scope.item['pCostPrice'];
      $scope.projectRabateList[v]['pSellingPrice'] = $scope.item['pSellingPrice'];
      $scope.projectRabateList[v]['pCostBackPrice']=$scope.item['pCostBackPrice'];
      $scope.projectRabateList[v]['pCoreBackPrice']=$scope.item['pCoreBackPrice'];
      $scope.projectRabateList[v]['pBackSellingPrice']=$scope.item['pBackSellingPrice'];
      $scope.projectRabateList[v]['pBackRabateProfit']=$scope.item['pBackRabateProfit'];

      //20180408   核心价和后端核心价后端成本价前台隐藏，给默认值
      $scope.projectRabateList[v]['pCorePrice']=$scope.projectRabateList[v]['pCostPrice'];
      $scope.projectRabateList[v]['pCoreBackPrice']=$scope.projectRabateList[v]['pCostPrice'];
      $scope.projectRabateList[v]['pCostBackPrice']=$scope.projectRabateList[v]['pCostPrice'];
    }


    $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pCostBackPrice:[],pCoreBackPrice:[],pBackSellingPrice:[],pBackRabateProfit:[] };
    angular.forEach($scope.projectAnnualRevenue,function(o,i){
      $scope.formData['pId'].push(o['pId']);
      $scope.formData['pRebateType'].push("01");
      $scope.formData['pStartAmount'].push(o['pStartAmount']);
      $scope.formData['pEndAmount'].push(o['pEndAmount']);
      $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
      $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
      $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
      $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
      $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);
      $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
      $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
      $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);
      $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);

      $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
    });

    $scope.formData2 = {id:$scope.id};
    for (k in $scope.formData){
      $scope.formData2[k] = $scope.formData[k].join(",");
    }
    console.log($scope.formData2);
    productService.productProfitUpdate($scope.formData2).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("操作成功");
        $scope.item = {};
        $scope.item.pIsAgreement = "0";
        $scope.itemIndex = undefined;

        //刷新日志
        queryEditLog();
      }
    });
  };
}]);

faApp.controller('ProductAttachCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.attachs = [];

  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
  });
  productService.productAttachList($scope.id).then(function(json){
    $scope.loading = false;
    $scope.attachs = json.projectAttachmentsList;
  });

  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item['fName'] = $scope.attachs[v]['fName'];
    $scope.item['fileUrl'] = $scope.attachs[v]['fPath'];
    $scope.item['fileType'] = $scope.attachs[v]['fType'];
  };

  $scope.deleteItem = function(v){
    $scope.attachs.splice(v,1);
    if (v > $scope.itemIndex){
      $scope.itemIndex --;
    }
    $scope.save(true);
  };

  $scope.save = function(deleteFlag){
    if (!deleteFlag){
      var v = $scope.itemIndex;
      if (v == undefined){
        if ($scope.attachs.length < 1){
          v = 0;
        }else{
          v = $scope.attachs.length;
        }
        $scope.attachs[v] = {pId:$scope.id};
      }
      $scope.attachs[v]['fName'] = $scope.item['fName'];
      $scope.attachs[v]['fPath'] = $scope.item['fileUrl'];
      $scope.attachs[v]['fType'] = $scope.item['fileType'];
    }

    $scope.formData = {fName:[],fileUrl:[],fileType:[]};
    angular.forEach($scope.attachs,function(o,i){
      if (o['fName'] && o['fPath'] && o['fType']){
        $scope.formData['fName'].push(o['fName']);
        $scope.formData['fileUrl'].push(o['fPath']);
        $scope.formData['fileType'].push(o['fType']);
      }
    });


    $scope.formData2 = {pId:$scope.id};
    for (k in $scope.formData){
      $scope.formData2[k] = $scope.formData[k].join(",");
    }

    productService.productAttachUpdate($scope.formData2).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.addAlert("操作成功");
        $scope.item = {};
        $scope.itemIndex = undefined;
      }
    });
  };

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    type:'productFile',
    refid:$scope.id,
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.fileUrl = response.attribute.fileUrl;
        $scope.item.fileType = response.attribute.fileType;
        $scope.item.fName = response.attribute.fName;
        $scope.$apply();
      } else if (response.statusCode == "0003") {
        alert('格式不正确');
      } else {
        alert('上传失败');
      }
    }
  });
}]);


faApp.controller('ProductNoiceCtrl',['$scope','productService','$location','$controller','$routeParams','$filter',function($scope,productService,$location,$controller,$routeParams,$filter) {
    $controller('BaseCtrl', {$scope: $scope});
    $scope.id = $routeParams.id;
    console.info("产品ID："+$scope.id)

    $scope.item = {};
    $scope.attachs = [];

    $scope.loading = true;
    productService.productQuery($scope.id).then(function(json){
        $scope.project = json.project;
    });

    queryFileList();//查询附件信息
    function queryFileList() {
        productService.productNoticeQuery({"refid":$scope.id, "type":"productNotice"}).then(function(json){
          console.info("产品公告附件：")
          console.info(json.list)

            $scope.loading = false;
            $scope.attachs = json.list;
        });
    }

    $scope.deleteItem = function(d, index){

        if(d.id) {
            $scope.loading = true;
            productService.productNoticeDelete({id:d.id}).then(function (json) {
              if(json.statusCode=='2002') {
                alert("参数缺失!");
              } else {
                  $scope.attachs.splice(index, 1);

                  $scope.loading = false;
                  $scope.addAlert("删除成功");
              }
            });
        }
    };

    $scope.onUploadFile({
        showMessage : function(m){ alert(m); },
        type:'productNotice',
        refid:$scope.id,
        onComplete:function(f,response){
            if (response.statusCode == "0000") {
                // $scope.item.fileUrl = response.attribute.fileUrl;
                // $scope.item.fileType = response.attribute.fileType;
                // $scope.item.fName = response.attribute.fName;
                // $scope.$apply();
                queryFileList();
            } else if (response.statusCode == "0003") {
                alert('格式不正确');
            } else {
                alert('上传失败');
            }
        }
    });
}]);

faApp.controller('ProductChooseRecommendList',['$scope','productService','$location','$controller','$route','adService','$routeParams',function($scope,productService,$location,$controller,$route,adService, $routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.recommendList = [];

  $scope.$watch('config',function(){
    adService.adRecommendList($scope.config).then(function(json){
      $scope.recommendList = json.list;
      // $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.config = {
    "pageSize" : 100,
    "pageNo" : 1,
    "advertPosition" : $routeParams.t || '10'
  };

  $scope.toAddRecommend = function(){
    if($scope.recommendList && $scope.recommendList.length >= 5){
      alert("最多能有五项！");
      return;
    }else{
      $location.path("/chooseRecommend/add").search({t : $scope.config.advertPosition || '10'});
    }
  }

  $scope.start = function(id){
    adService.adStart({id:id,status:"01"}).then(function(json){
      $route.reload();
    });
  };

  $scope.stop = function(id){
    var t = 0;
    angular.forEach($scope.recommendList,function(o){
      if(o.status == '01')
        t++;
    });
    if(t <= 2){
      alert("最少得有两项！");
      return;
    }
    adService.adStop({id:id,status:"02"}).then(function(json){
      $route.reload();
    });
  };

}]);

faApp.controller('ProductChooseRecommendAdd', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams', function($scope, productService, $location, $controller, $route, adService, $routeParams) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {
    title:'',
    pic:'',
    linkAddre:'',
    startTime:'1990-01-01 00:00:00',
    endTime:'3000-01-01 23:59:59',
    status:'01',
    advertSort:'1',
    picAddre:'',
    advertPosition: $routeParams.t || '10'
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adAdd($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/chooseRecommend/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

}]);

faApp.controller('ProductChooseRecommendEdit', ['$scope', 'productService', '$location', '$controller', '$route', 'adService', '$routeParams','$filter' , function($scope, productService, $location, $controller, $route, adService, $routeParams, $filter) {
  $controller('BaseListCtrl', { $scope: $scope });

  $scope.recommend = {};
  $scope.id = $routeParams.id;

  if($scope.id){
    adService.adQuery($scope.id).then(function(json){
      $scope.recommend = json.dto;

      $scope.recommend.startTime = $filter("date")($scope.recommend.startTime,"yyyy-MM-dd") + " 00:00:00";;
      $scope.recommend.endTime = $filter("date")($scope.recommend.endTime,"yyyy-MM-dd") + " 23:59:59";
    });
  }

  $scope.save = function(){
    if (!$scope.form.$invalid){
      if(!$scope.recommend.picAddre && $scope.recommend.advertPosition != '14'){
        alert("请上传图片!");
        return;
      }
      adService.adEdit($scope.recommend).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          $location.path("/chooseRecommend/list").search({t : $scope.recommend.advertPosition});
        }
      });
    }else{
      alert("请把信息填写完整！");
    }
  }

  $scope.onUploadFile({
    showMessage: function(m) { alert(m); },
    onComplete: function(f, response, id) {
      if (response.statusCode == "0000") {
        $scope.recommend.picAddre = response.attribute.fileUrl;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });
}]);

faApp.controller('ProductVideoCtrl',['$scope','productService','roadVideoService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,roadVideoService,$location,$controller,$routeParams,$filter,$route) {

  $controller('BaseCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  $scope.spnr = {};
  $scope.player = '';

  roadVideoService.list({isProduct:'0',pageSize:1000,pageNo:1}).then(function(json){
    $scope.list = json.list;
  });
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    $scope.videoInfoPost = {
      productType:$scope.product.pType,
      productId:$scope.product.id
    };
    roadVideoService.videoIdbyPro($scope.videoInfoPost).then(function(json){
      $scope.oldId = json.dto ? json.dto.id : '';
      $scope.title = json.dto ? json.dto.title : '';

    });
  });



  $scope.save=function(){
    if($scope.newVideoId==null||$scope.newVideoId==''){
      alert("视频名称不能为空");
      return ;
    }
    $scope.spnr.productType=$scope.product.pType;
    $scope.spnr.productId=$scope.id;
    $scope.spnr.id = $scope.newVideoId;
    $scope.spnr.oldId = $scope.oldId;
    roadVideoService.edit($scope.spnr).then(function(json){
      if(!json.statusCode){
        alert("修改成功");
        $route.reload()
      }else{
        alert(json.statusCode);
      }
    });
  }

  $scope.playVideo = function(v){
    if(!v){
      alert('请选择视频');
      return;
    }else{
      for( arr in $scope.list){
        if($scope.list[arr].id == v){
          $scope.videoId = $scope.list[arr].videoId;
        }
      };
    };
    if($scope.videoId){
      $scope.showPlayBox = true;
      $scope.player = new YKU.Player('youkuplayer',{
        styleid: '0',
        client_id: YK_CLIENT_ID,
        vid: $scope.videoId,
        newPlayer: true
      })
    }
  }
  $scope.stopPlay = function(){
    $scope.videoId = '';
    $scope.showPlayBox = false;
  }




}]);

faApp.controller('ProductNoticeListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.chkProjectNoticeAll = function(){
    if($("#chkProjectNoticeAll").attr("checked") == "checked"){
      $("[name='chkProjectNotice']").attr("checked","checked");
    }else{
      $("[name='chkProjectNotice']").attr("checked",false);
    }
  }
  $scope.$watch('config',function(){
    productService.queryProductNoticeList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true);

  $scope.del = function(id){
    if(confirm("确认删除???")){
      $scope.config.id=id;
      $scope.config.deleteTag=2;
      productService.editProductNotice($scope.config).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
           alert("删除成功!!");
           $route.reload();
        }
      });
    }
   
  }
  $scope.allDel = function(){
    var id="";
    $("[name='chkProjectNotice']").each(function(){
      if($(this).attr("checked") == "checked"){
          id += $(this).attr("value")+",";
      }
    });
    if(!id){
      alert("请选择资讯!!!");
      return ;
    }
    if(confirm("确认全部删除???")){
      id = id.substring(0, id.length - 1);
      $scope.config.id=id;
      $scope.config.deleteTag=2;
      productService.editProductNotice($scope.config).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
           alert("删除成功!!");
           $route.reload();
        }
      });
    }
   
  }
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };   
}]);

faApp.controller('ProductNoticeDetailCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService','$sce',function($scope,productService,$location,$controller,$route,$routeParams,sessionService,$sce) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.config={};
  $scope.config.id = $routeParams.id;
  productService.queryProductNoticeDetail($scope.config).then(function(json){
      $scope.productNotice = json.queryProdcutNoticeDetail;
      $scope.productNotice.pContent=$sce.trustAsHtml($scope.productNotice.pContent);
      $scope.loading = false;
    });
   $scope.del = function(id){

    // $location.path("/productnotice/list");
      if(confirm("确认删除???")){
        $scope.config.id=id;
        $scope.config.deleteTag=2;
        productService.editProductNotice($scope.config).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            alert("删除成功!!");
            // $location.path("#/productnotice/list");
            window.parent.location = "#/productnotice/list";
          }

        });
      }

   }

   $scope.passVerifyable=function (id) {
    $scope.productNotice={};
    $scope.productNotice.id=id;
    $scope.productNotice.status=2;
    productService.editProductNotice($scope.productNotice).then(function(json){
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("审核成功!!");
          $route.reload();
         // window.parent.location = "#/productnotice/list";
        }
    });
   }
  $scope.productPassPublish=function (id) {
    $scope.productNotice={};
    $scope.productNotice.id=id;
    $scope.productNotice.onlineStatus=2;
    productService.editProductNotice($scope.productNotice).then(function(json){
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发布成功!!");
          window.parent.location = "#/productnotice/list";
          //$route.reload();
        }
    });
   }
}]);

faApp.controller('ProductNoticeEditCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.config={};
  $scope.config.id = $routeParams.id;
  productService.queryProductNoticeDetail($scope.config).then(function(json){
      $scope.productNotice = json.queryProdcutNoticeDetail;
      $scope.loading = false;
  });

  $scope.save = function(){
    productService.editProductNotice($scope.productNotice).then(function(json){
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("编辑成功!!");
          if($scope.productNotice.onlineStatus==1){
            window.parent.location ="#/productnotice/base?id=" + $scope.productNotice.id;
          }else{
            window.parent.location = "#/productnotice/list";
          }
          //$route.reload();
        }
    });
  }

}]);


faApp.controller('ProductNoticeBaseCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  
  $scope.id = $routeParams.id;
  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    detailUrl : "#/productnotice/detail?id=" + $scope.id,
    editUrl : "#/productnotice/edit?id=" + $scope.id
  };
  
  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };
  
  var lastProductTab = sessionService.getItem('lastProductTab') || 'detailUrl'; 
  $scope.changeTab('detailUrl');
  
  $scope.pathText ="成立公告"; 
  
  angular.element(document).ready(function(){
    // console.log(1);
    if ($(window).height() > 300) $scope.iframeHeight = $(window).height() - 130;
  });

}]);



faApp.controller('ProductOrderDataCtrl',['$scope','simuOrderService','orderService','$location','$controller','$route','$routeParams',function($scope,simuOrderService,orderService,$location,$controller,$route,$routeParams){   

  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = {};
  $scope.loading = true;
  $scope.pType=$routeParams.pType;
  $scope.proId=$routeParams.proId;
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "oProjectId" : 0,
    "productId":0
  };
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };

  if($scope.pType=="05"){
    simuOrderService.listByProId($scope.config,$scope.proId).then(function(json){
      $scope.list = json.list;
      $scope.oType="03";
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  }else if($scope.pType=="02"||$scope.pType=="03"){
    orderService.listByProId($scope.config,$scope.proId).then(function(json){
      if($scope.pType=="02"){
        $scope.oType="01";
      }else if($scope.pType=="03"){
        $scope.oType="02";
      }
      $scope.list = json.orderList;
      $scope.pager = json.page;
      $scope.loading = false;
    });
  }else if($scope.pType=="06"){
    orderService.listByProId($scope.config,$scope.proId).then(function(json){
      $scope.oType="06";
      $scope.list = json.orderList;
      $scope.pager = json.page;
      $scope.loading = false;
    });
  }


}]);
faApp.controller('editProductOrderDataCtrl',['$scope','orderPhoService','$location','$controller','$route','$routeParams',function($scope,orderPhoService,$location,$controller,$route,$routeParams){   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;
  $scope.config = {};
  $scope.config.pType=$routeParams.pType;//产品类型
  $scope.config.pId=$routeParams.pId;//产品id
  $scope.config.oId=$routeParams.oId;//订单id
  $scope.config.oType=$routeParams.oType;//订单类型
  $scope.k=$routeParams.k;//标题
  $scope.role=$routeParams.role;//角色
    $scope.head=$routeParams.head;//是否显示头部
  console.log($scope.k);

  orderPhoService.query($scope.config).then(function(json){
    $scope.list=json.list;
    $scope.loading=false;
  });

  $scope.showEstablishaFormFlag=false;

  $scope.changePic=function(v){
    $scope.pic=v;
    $scope.showEstablishaFormFlag=false;
  }
  $scope.toBack=function(v){
    $scope.oPhoId=v;
    $scope.oPhoReason="";
    $scope.showEstablishaFormFlag=true;
  }
  $scope.confirmCommit=function(v){
    $scope.config = {};
    $scope.config.id=v;
    $scope.config.oPhoStatus="03";
    orderPhoService.edit($scope.config).then(function(json){
      if(!json.statusCode){
        //alert("审核成功");
        $scope.showEstablishaFormFlag=false;
      }else{
        alert("审核失败！"+json.statusCode);
      }
      $route.reload();
    });
  }
  //全部一键通过
  $scope.confirmCommitAll=function(){
    
        angular.forEach($scope.list, function(data,index){
          $scope.config = {};
          $scope.config.id=data.oPhoId;
          $scope.config.oPhoStatus="03";
          orderPhoService.edit($scope.config).then(function(json){
            if(!json.statusCode){
              //alert("审核成功");
              $scope.showEstablishaFormFlag=false;
            }else{
              alert("审核失败！"+json.statusCode);
            }
            if((index+1) == $scope.list.length){
              $route.reload();
            }
           
          });
        });
  }
  $scope.confirmReason=function(v){
    if($scope.oPhoReason==""){
      alert("原因必填!!");
      return ;
    }
    $scope.config = {};
    $scope.config.oPhoReason=$scope.oPhoReason;
    $scope.config.id=$scope.oPhoId;
    $scope.config.oPhoStatus="04";
    orderPhoService.edit($scope.config).then(function(json){
      if(!json.statusCode){
        //alert("审核成功");
        $scope.showEstablishaFormFlag=false;
      }else{
        alert("审核失败！"+json.statusCode);
      }
      $route.reload();
    });
  }

}]);

faApp.controller('ReportBaseCtrl',['$scope','productService','reportService','$location','$controller','$route','$routeParams','$filter',
function($scope,productService,reportService,$location,$controller,$route,$routeParams,$filter) {
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;
  $scope.t = $routeParams.t;
  $scope.pCode = "";

  //产品解析报告
  $scope.report = {};
  $scope.resume = {};           //项目概要
  $scope.structureDiagram = []; //结构图
  $scope.repaymentSource = {};  //还款来源
  $scope.fundsUse = {};         //资金用途
  $scope.riskControl = [];      //风控措施
  $scope.lenders = [];          //融资方
  $scope.issuers = {};          //发行方
  $scope.relevantData = [];     //相关资料

  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    xmgyUrl : "/report/xmgy?id=" + $scope.pid,
    jgtUrl  : "/report/jgt?id="  + $scope.pid,
    hklyUrl : "/report/hkly?id=" + $scope.pid,
    zjytUrl : "/report/zjyt?id=" + $scope.pid,
    fkcsUrl : "/report/fkcs?id=" + $scope.pid,
    rzfUrl  : "/report/rzf?id="  + $scope.pid,
    fxfUrl  : "/report/fxf?id="  + $scope.pid,
    xgzlUrl : "/report/xgzl?id=" + $scope.pid,
  };

  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
  };
  $scope.changeTab('xmgyUrl');

  //根据ID加载产品信息
  productService.productQuery($scope.pid).then(function(json){
    $scope.product = json.project;

    // 产品ID保存到产品分析中
    $scope.report["fpProductId"] = json.project.id;
    $scope.pCode = json.project.pCode;

    // 项目概要tab中显示融资方
    $scope.resume['productLendersName'] = $scope.resume['productLendersName'] || $scope.product.pProjectOwner;
  });

  $scope.reportPost = function(){
    if($scope.pid){

      reportService.deepAnalyticsDetail($scope.pid).then(function(json){
        if(!json.dto){
          alert("产品解析报告为空，请添加内容之后再发布！");
          return;
        }else if(!json.dto['fpProductResume']){
          alert("项目概要为空！");
          return;
        }else if(!json.dto['fpProductStructureDiagram']){
          alert("结构图为空！");
          return;
        }else if(!json.dto['fpProductRepaymentSource']){
          alert("还款来源为空！");
          return;
        }else if(!json.dto['fpProductRiskControl']){
          alert("风控措施为空！");
          return;
        }else if(!json.dto['fpProductLenders']){
          alert("交易对手为空！");
          return;
        }else if(!json.dto['fpProductFundsUse']){
          alert("资金用途为空！");
          return;
        }else if(!json.dto['fpProductIssuers']){
          alert("发行方为空！");
          return;
        }else if(!json.dto['fpProductRelevantData']){
          alert("相关资料为空！");
          return;
        }

        reportService.deepAnalyticsSave({"fpProductId":$scope.pid,"fpProductStatus":"1"}).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            alert("发布成功！");
          }
        });

      });

    }else{
      alert("产品ID为空，请刷新页面重试！");
    }
  }

  $scope.reportPostCancel = function(){
    if($scope.pid){
      reportService.deepAnalyticsSave({"fpProductId":$scope.pid,"fpProductStatus":"2"}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("取消发布成功！");
        }
      });
    }else{
      alert("产品ID为空，请刷新页面重试！");
    }
  }

  $scope.previewReport = function(){
    if($scope.pCode){
      //alert("111" + $scope.pCode);
      // window.open(App.staticHost + "/product/analyse3/" + $scope.pCode + "?preview=true");
      window.open(App.staticHost + "/analyse4/" + $scope.pCode + "?preview=true");
    }else{
      alert("页面出错，请刷新页面重试！");
    }
  }
}]);

faApp.controller('ReportXmgyCtrl',['$scope','productService','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;

  // 根据产品ID查询解析报告
  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }
    
    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductResume']){      
      $scope.resume = angular.fromJson(json.dto['fpProductResume'] || {});
    }
  });

  $scope.save = function(){
    //alert($scope.form.);
    //sessionService.setItem('reportResume',angular.toJson($scope.resume));
    $scope.report["fpProductResume"] = angular.toJson($scope.resume);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportJgtCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;
  $scope.structureDiagram = [];
  $scope.xsjt = "";
  $scope.xxjt = "";
  $scope.zydy = [];
  $scope.dbfs = [];
 
  $scope.structureDiagram.push({"xsjt": $scope.xsjt});
  $scope.structureDiagram.push({"xxjt": $scope.xxjt});

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];
    $scope.resume = angular.fromJson(json.dto['fpProductResume'] || {});

    if(json.dto['fpProductStructureDiagram']){
      
      $scope.structureDiagram = angular.fromJson(json.dto['fpProductStructureDiagram'] || []);

      $scope.zydy = $scope.structureDiagram[0].zydy;
      $scope.dbfs = $scope.structureDiagram[1].dbfs;

      $scope.xsjt = $scope.structureDiagram[2].xsjt;
      $scope.xxjt = $scope.structureDiagram[3].xxjt;
      // if(!$scope.structureDiagram){
      //   $scope.structureDiagram = [];
      //   $scope.riskControl.push({"zydy": zydy});
      //   $scope.riskControl.push({"dbfs": dbfs});
      // }
    }
  });

  $scope.addZydy = function(){
    if($scope.zydy.length < 3){
      $scope.zydy.push({"zydy":""});
    }else{
      alert("最多添加三条！");
    }
  };

  $scope.deleteZydy = function(i){
    $scope.zydy.splice(i, 1);
  };

  $scope.addDbfs = function(){
    if($scope.dbfs.length < 3){
      $scope.dbfs.push({"dbfs":""});
    }else{
      alert("最多添加三条！");
    }
  };

  $scope.deleteDbfs = function(i){
    $scope.dbfs.splice(i, 1);
  };

  $scope.save = function(){
    $scope.structureDiagram = [];

    $scope.structureDiagram.push({"zydy": $scope.zydy});
    $scope.structureDiagram.push({"dbfs": $scope.dbfs});
    $scope.structureDiagram.push({"xsjt": $scope.xsjt});
    $scope.structureDiagram.push({"xxjt": $scope.xxjt});

    $scope.report["fpProductStructureDiagram"] = angular.toJson($scope.structureDiagram);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportHklyCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductRepaymentSource']){
      $scope.repaymentSource = angular.fromJson(json.dto['fpProductRepaymentSource'] || {});
    }
  });

  $scope.save = function(){
    $scope.report["fpProductRepaymentSource"] = angular.toJson($scope.repaymentSource);
    // console.log($scope.repaymentSource);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportZjytCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductFundsUse']){
      $scope.fundsUse = angular.fromJson(json.dto['fpProductFundsUse'] || {});
    }
  });

  $scope.save = function(){
    $scope.report["fpProductFundsUse"] = angular.toJson($scope.fundsUse);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportFkcsCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;
  $scope.dbfsAll = [];
  $scope.dbfx = "";
  var kzbgTmp = [{"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""},
                 {"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""},
                 {"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""},
                 {"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""},
                 {"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""},
                 {"kzbg1":"","kzbg2":"","kzbg3":"","kzbg4":""}];

  $scope.riskControl.push({"dbfx": ""});
  $scope.riskControl.push({"kzbg": kzbgTmp});

  $scope.kzbgAll = kzbgTmp;

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductRiskControl']){
      $scope.riskControl = angular.fromJson(json.dto['fpProductRiskControl'] || []);

      $scope.dbfsAll = $scope.riskControl[0].dbfs;

      $scope.dbfx = $scope.riskControl[1]['dbfx'] || "";
      $scope.kzbgAll = $scope.riskControl[2]['kzbg'].length > 0 ? $scope.riskControl[2]['kzbg'] : kzbgTmp;
    }

    // console.log($scope.riskControl[1]['kzbg']);
  });

  $scope.addDbfs = function(){
    if($scope.dbfsAll.length < 8){
      $scope.dbfsAll.push({"bt":"","ms":""});
    }else{
      alert("最多添加八条！")
    }
  };

  $scope.deleteDbfs = function(i){
    $scope.dbfsAll.splice(i, 1);
  };

  $scope.save = function(){
    var isShow = true;
    $scope.riskControl = [];

    $scope.riskControl.push({"dbfs":$scope.dbfsAll});
    $scope.riskControl.push({"dbfx":$scope.dbfx});

    for (var i = 0; i < $scope.kzbgAll.length; i++) {
      if($scope.kzbgAll[i]['kzbg1'] || $scope.kzbgAll[i]['kzbg2'] ||
         $scope.kzbgAll[i]['kzbg3'] || $scope.kzbgAll[i]['kzbg4']){
        isShow = false;
        break;
      }
    };

    $scope.riskControl.push({"kzbg": isShow ? [] : $scope.kzbgAll});

    $scope.report["fpProductRiskControl"] = angular.toJson($scope.riskControl);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportRzfCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;
  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductLenders']){

      $scope.lenders = angular.fromJson(json.dto['fpProductLenders'] || []);
      for(i in $scope.lenders){
        $scope.lenders[i].shareHolder = $scope.lenders[i].shareHolder || [{gdxx: '',gdlx: '',gd: '',zjlx: '',zjhm: ''}];
      };
      console.log($scope.lenders);
    }
  });
  $scope.addLenders = function(){
    $scope.lenders.push({"zch":"","gsmc":"","lx":"","fddb":"","zs":"","zczb":"","clrq":"","jyqxf":"","jyqxt":"","jjfw":"","fjjg":"","hzrq":"","djzt":"","shareHolder":[{'gdxx' : '','gdlx' : '','gd': '','zjlx' : '','zjhm' : ''}]});
  };
  var shareHolderIndex = 1;
  $scope.addShareHolder = function(i){
    $scope.lenders[i].shareHolder.push({gdxx : '',gdlx : '',gd : '',zjlx : '',zjhm : ''});
  }
  $scope.deleteShareHolder = function(p,i){
    $scope.lenders[p].shareHolder.splice(i, 1);
    $scope.save();
  }
  $scope.deleteLenders = function(i){
    $scope.lenders.splice(i, 1);
  };

  $scope.save = function(){
    $scope.report["fpProductLenders"] = angular.toJson($scope.lenders);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportFxfCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductIssuers']){
      $scope.issuers = angular.fromJson(json.dto['fpProductIssuers'] || {});
    }
  });

  $scope.save = function(){
    $scope.report["fpProductIssuers"] = angular.toJson($scope.issuers);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);

faApp.controller('ReportXgzlCtrl',['$scope','reportService','$location','$controller','$route','$routeParams','sessionService',function($scope,reportService,$location,$controller,$route,$routeParams,sessionService) {
  $controller('ReportBaseCtrl', {$scope: $scope});
  $scope.pid = $routeParams.id;

  reportService.deepAnalyticsDetail($scope.pid).then(function(json){
    if(!json.dto){
      return;
    }

    $scope.report['id'] = json.dto['id'];

    if(json.dto['fpProductRelevantData']){
      $scope.relevantData = angular.fromJson(json.dto['fpProductRelevantData'] || []);
    }
  });

  $scope.addRelevantData = function(){
    if($scope.relevantData.length >= 10){
      alert("资讯最多十条！");
      return;
    }
    $scope.relevantData.push({"zxbt":"","zxdz":""});
  };

  $scope.deleteRelevantData = function(i){
    if($scope.relevantData.length <= 2){
      alert("资讯最低两条！");
      return;
    }
    $scope.relevantData.splice(i, 1);
  };

  $scope.textChange = function(o){
    var t = $("#" + o).val();
    if(t != undefined && t.length > 28){
      $("#" + o).val(t.substr(0,28));
      alert("资讯标题最多28个字，已自动截取！");
    }
  }

  $scope.save = function(){
    $scope.report["fpProductRelevantData"] = angular.toJson($scope.relevantData);
    reportService.deepAnalyticsSave($scope.report).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("保存成功！");
        $route.reload();
      }
    });
  }
}]);
faApp.controller('roadVideoAddCtrl',['$scope','$location','$controller','$route','$filter','$routeParams','roadVideoService','userService','productService','simuService',function($scope,$location,$controller,$route,$filter,$routeParams,roadVideoService,userService,productService,simuService) {
  $controller('BaseCtrl', {$scope: $scope});

  $scope.id = $routeParams.id;

  $scope.item = {'isEncryption':1};
  $scope.player = '';

  if($scope.id){
    roadVideoService.detailById($scope.id).then(function(json){
      if (json.statusCode){
        alert(json.statusCode);
      }else{
        $scope.item = json.dto;
      }
    });
  };

  var tmpType = '';
  $scope.$watch('item.productType', function() {
    if($scope.item.productType && ($scope.item.productType == '04')){
      alert('暂不支持此类型！');
      $scope.item.productType = tmpType;
      tmpType = '';
      return;
    }

    if($scope.item.productType && (tmpType != $scope.item.productType)){
      $scope.loading = true;
      tmpType = $scope.item.productType;
      var param = {
        pageNo:1, 
        pageSize:1000,
        pTypeList: $scope.item.productType, 
        pPublicStatus:'2',
        activitiesCode:'lysp',
        videoId : $scope.item.id || ''
      };
      if($scope.item.productType == '01'){
        param.pubStatus = 1;
      };
      // 根据类型查询对应的产品列表
      if($scope.item.productType == '06'){
        // PE/VC
        
        productService.queryProductList(param).then(function(json){
          $scope.productList = json.list;

          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }else if($scope.item.productType == '02' || $scope.item.productType == '03'){
        // 信托资管
        productService.productList(param).then(function(json){
          $scope.productList = json.projectList;
          
          // 删除已经添加的！
          // exclude();
          
          $scope.loading = false;
        });
      }else if($scope.item.productType == '01'){
        // 阳光私募
        simuService.list(param).then(function(json){
          $scope.productList = json.list;
          
          // 删除已经添加的！
          // exclude();

          $scope.loading = false;
        });
      }
    }
  }, true);

  $scope.onUploadFile({
    showMessage: function(m) {
      alert(m);
    },
    onComplete: function(f, response, id) {
      console.log(id);
      id--;
      if (response.statusCode == "0000") {
        if (id == 0) {
          $scope.item.imagePath = App.staticHost + response.attribute.fileUrl;
          $scope.$apply();
        } else if (id == 1) {
          $scope.item.imagePathForProduct = App.staticHost + response.attribute.fileUrl;

          $scope.$apply();
        } else if(id == 2) {
          $scope.item.shareImage = App.staticHost + response.attribute.fileUrl;
          $scope.$apply();
        }else {
          alert('上传失败');
        }
      }
    }
  });

  $scope.save = function() {
    if ($scope.form.$invalid) {
      alert('填写必填项');
    }else if($scope.item.title.length>20){
        alert('视频标题最多输入20个字符');
    }else{
      if($scope.id){
        roadVideoService.edit($scope.item).then(function(json){
          if(json.statusCode){
            alert(json.statusCode)
          }else{
            alert('修改成功');
            $route.reload()
          }
        });
      }else{
        if($scope.item.productType == '01'){
          $scope.item.pubStatus = 1;
        };
        roadVideoService.add($scope.item).then(function(json){
          if(json.statusCode){
            alert(json.statusCode)
          }else{
            $location.path('/roadVideo/list');
          }
        });
      };
    }
  };

  $scope.products = [];
  $scope.searchProduct = function() {
    $scope.showSearchCombox = true;
    $scope.loaded = false;
    // productService.productList({pPublicStatus:2,pName:$scope.productKw,pSaleStatus:'03'}).then(function(json){
    productService.productList({
      pPublicStatus: 2,
      pName: $scope.productKw
    }).then(function(json) {
      $scope.products = json.projectList;
      $scope.pager = json.projectDTO;
      $scope.loaded = true;
    });
  };

  $scope.selectProduct = function(id) {
    $scope.item.pId = id;

    angular.forEach($scope.products, function(o) {
      if (o.id == id) {

        millionService.list({
          pId: id,
          activitiesCode: $scope.item.activitiesCode
        }).then(function(json) {
          if (json && json.list && json.list.length > 0) {
            alert("此产品已经在参与活动了");
            $scope.productKw = "";
            return;
          } else {
            $scope.product = o;
            $scope.productKw = o.pName;

            productService.productQuery($scope.product.id).then(function(json) {
              $scope.product = json.project;
              $scope.loading = false;
              $scope.projectRabateList = json.projectRabateList;
              $scope.minRebate = 99999999;
              if ($scope.projectRabateList && $scope.projectRabateList.length > 0) {
                angular.forEach($scope.projectRabateList, function(o) {
                  if (o.pRabateProfit < $scope.minRebate) {
                    $scope.minRebate = o.pRabateProfit;
                  }
                });
              }
            });
          }
        });

        $scope.showSearchCombox = false;
      }
    });
  };

  $scope.playVideo = function(v){
    if(!v){
      alert('输入视频ID');
      return;
    }else{
      $scope.showPlayBox = true;
      $scope._videoId = v;
      $scope.player = new YKU.Player('youkuplayer',{
        styleid: '0',
        client_id: YK_CLIENT_ID,
        vid: $scope._videoId,
        newPlayer: true
      })
    }
  }
  $scope.stopPlay = function(){
    $scope._videoId = '';
    $scope.showPlayBox = false;
  }
  
}]);

faApp.controller('roadVideoListCtrl',['$scope','$location','$controller','$route','roadVideoService',function($scope,$location,$controller,$route,roadVideoService) {
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.loading = true;

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.newsList = {};
  $scope.$watch('config',function(){
    roadVideoService.list($scope.config).then(function(json){
      $scope.list = json.list || '';
      $scope.pager = json.pager;
      for( i in $scope.list){
        if($scope.list[i].isEncryption == 1){
          $scope.encryptionPassword = $scope.list[i].encryptionPassword;
          return;
        }else{
          $scope.encryptionPassword = '';
        }
      }

    });
  },true);

  $scope.search = function() {
    angular.forEach($scope.searchMap, function(o, i) {
      $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    $scope.config.pageNo = 1;
  };

  $scope.delete = function(id){
    if(confirm('确定删除？')){
      roadVideoService.delete(id).then(function(json) {
        if (json.statusCode) {
          alert(json.statusCode)
        } else {
          $route.reload();
        }
      })
    }

  };

  $scope.orderby = function(v){
    if(v == 'createDate'){
      $scope.config.orderParameter = '01';
    }else if(v == 'updateDate'){
      $scope.config.orderParameter = '02';
    }else if(v == 'playNum'){
      $scope.config.orderParameter = '03';
    };
    if($scope.config.orderType == '01'){
      $scope.config.orderType = '02';
    }else{
      $scope.config.orderType = '01';
    }

  };

  $scope.saveEncryptionPassword = function(){
    if($scope.encryptionPassword){
      roadVideoService.videoPassword($scope.encryptionPassword).then(function(json){
        if(json.statusCode){
          alert('json.statusCode');
        }else{
          alert('密码修改成功');
        }
      })
    }
  }

}]);

faApp.controller('roadVideoPlayCtrl',['$scope','$location','$controller','$route','roadVideoService',function($scope,$location,$controller,$route,roadVideoService) {
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.id = $routeParams.id;
  player = new YKU.Player('youkuplayer',{
    styleid: '0',
    client_id: 'YOUR YOUKUOPENAPI CLIENT_ID',
    vid: '替换成优酷视频ID',
    newPlayer: true
  });


}]);
faApp.controller('SaleconListCtrl',['$scope','licaishiManagerService','caleconService','exportService','$location','$controller','$route', '$filter', function($scope,licaishiManagerService,caleconService,exportService,$location,$controller,$route, $filter) {
  $controller('BaseListCtrl', {
    $scope: $scope
  });
  var nowTime = new Date();
  var year = nowTime.getFullYear();
  var month = nowTime.getMonth()+1;
  var month = month > 9 ? month : '0' + month;
  var day = nowTime.getDate() > 9 ? nowTime.getDate() : '0' + nowTime.getDate();
  nowTime = year +'-'+ month +'-'+ day;

  $scope.searchMap = {
    dateStart:nowTime,
    dateEnd : nowTime
  }
  $scope.config = {
    pageSize : 20,
    pageNo : 1,
    dateStart : $scope.searchMap.dateStart,
    dateEnd : $scope.searchMap.dateEnd,
  }

  $scope.config1={"pageSize" : 10000}
  licaishiManagerService.list($scope.config1).then(function(json){
    if (json.statusCode){
      alert("出错了:" + json.statusCode);
    }else{
      $scope.licaishiManagerUserList = json.list;
    }
  });

  $scope.$watch('config',function(json){
    caleconService.getDataList($scope.config).then(function(json){
      if(json.statusCode){
        alert("出错了：+json.statusCode");
      }else{
        $scope.list = json.list;
      }
    })

  },true)

  $scope.export = function(){
    exportService.exportCSV($scope.config,"USER_SAlECON_CVS");
  };

}]);




faApp.controller('salesPrizesListCtrl',['$scope','salesPrizesService','$location','$controller','$routeParams','$filter','$route',function($scope,salesPrizesService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.item={salesPrizes:""};

  $scope.iteminfo={};

  $scope.submitAdd = function(){
    if(!$scope.item.salesPrizes){
      alert("请填写好内容!!");
      return ;
    }
    if(confirm("请确认更新所有奖项?")){
      try{
        var a = $scope.item.salesPrizes.split('\n');
        console.log(a);
        if(a[0].split(",").length>=2){
          console.log(a);
        }else{
          alert("格式不正确!!");
          return ;
        }
      }catch(e){
        console.log(e);
        alert("格式不能解析!!");
        return ;
      }
      
      salesPrizesService.salesPrizesAdd($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        alert("新增成功");
        $route.reload();
      }
    });
    }else{
      alert("填写内容");
    }
    
  }

  salesPrizesService.salesPrizesList($scope.config).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.iteminfo=json.list;
        $scope.pager = json.pager;
      }
    });


}]);

faApp.controller('salesPrizesPeopleListCtrl',['$scope','salesPrizesService','$location','$controller','$routeParams','$filter','$route',function($scope,salesPrizesService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.item={salesPrizesPeople:""};

  $scope.submitAdd = function(){
    if(!$scope.item.salesPrizesPeople){
      alert("请填写好内容!!");
      return ;
    }
    if(confirm("请确认更新所有人员?")){
      try{
        var a = $scope.item.salesPrizesPeople.split('\n');
        console.log(a);
        if(a[0].split(",").length>=2){
          console.log(a);
        }else{
          alert("格式不正确!!");
          return ;
        }
      }catch(e){
        console.log(e);
        alert("格式不能解析!!");
        return ;
      }
      
      salesPrizesService.salesPrizesPeopleAdd($scope.item).then(function(json){
      if (json.statusCode){
        if(json.statusCode=='4021'){
          alert("存在名单重复,"+json.phone);
        }else{
          alert("出错了:" + json.statusCode);
        }
        
      }else{
        alert("新增成功");
        $route.reload();
      }
    });
    }else{
      alert("填写内容");
    }
    
  }

  salesPrizesService.salesPrizesPeopleList($scope.config).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.iteminfo=json.list;
        $scope.pager = json.pager;
      }
    });
}]);
faApp.controller('SettingListCtrl',['$scope','settingService','$location','$controller','$route',
  function($scope,settingService,$location,$controller,$route) {   

    $controller('BaseCtrl', {$scope: $scope}); 

    $scope.settings = [];
    $scope.loading = true;

    $scope.$watch('config',function(){
      settingService.settingList($scope.config).then(function(json){
        $scope.settings = json.apiSettingList;
        $scope.pager = json.pager;
        $scope.loading = false;
      });
    },true);

    $scope.isEdit = {};
    $scope.settingsValue = {};

  // 显示编辑框
  $scope.toUpdate = function(id){
    $($scope.settings).each(function(i){
      $scope.isEdit[$scope.settings[i]['id']] = false;
    });

    $scope.isEdit[id] = true;
  };
  
  // 保存编辑内容
  $scope.updateValue = function(id){
    settingService.settingUpdate({id:id,settingValue:$scope.settingsValue[id]}).then(function(json){
      if(json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改成功！");
        $route.reload();
      }
    });
  }

}]);
faApp.controller('ShopUserCtrl', ['$scope', 'shopService', '$location', '$rootScope', '$controller', '$route', '$routeParams', 'exportService', 'licaishiManagerService', 'sessionService','$cookieStore','$cookies', function ($scope, shopService, $location, $rootScope, $controller, $route, $routeParams, exportService, licaishiManagerService, sessionService,$cookieStore,$cookies) {
    $scope.ctrlName = "ShopUserCtrl";
    $controller('BaseListCtrl', {$scope: $scope});
    $scope.fas = [];
    $scope.black = {blackType: 1};
    $scope.vtype = "";
    if ($routeParams.orderFlag == "1" && $routeParams.notHasVisit) {
        $scope.vtype = "成交客户列表";
    } else if ($routeParams.orderFlag == "2" && $routeParams.notHasVisit) {
        $scope.vtype = "待沉寂理财师列表";
    } else if ($routeParams.notHasVisit) {
        $scope.vtype = "待回访理财师列表";
    } else if ($routeParams.notHasCheck) {
        $scope.vtype = "待审核理财师列表";
    } else if ($routeParams.isnoManagerUserLicaishi) {
        $scope.vtype = "待分配理财师列表";
    } else {
        $scope.vtype = "所有理财师列表";
    }

    if($routeParams.newPage){
        console.info($routeParams.isEmptyParam)
        if($routeParams.isEmptyParam){
            $scope.searchMap={isnoManagerUserLicaishi:"",notHasVisit:""
                ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",systemUserId2:"",
                "pageSize" : 20,   "pageNo" : 1
            };
            $scope.config={isnoManagerUserLicaishi:"",notHasVisit:""
                ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",
                "pageSize" : 20,   "pageNo" : 1
            };
        }
        $scope.listWhere="";
        if($routeParams.isnoManagerUserLicaishi){//待分配
            $scope.searchMap.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
            $scope.config.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
            $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
        }
        if($routeParams.notHasVisit){//是否回访
            $scope.searchMap.notHasVisit=$routeParams.notHasVisit;
            $scope.config.notHasVisit=$routeParams.notHasVisit;
            $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
        }
        if($routeParams.notHasCheck){//待审核
            $scope.searchMap.notHasCheck=$routeParams.notHasCheck;
            $scope.config.notHasCheck=$routeParams.notHasCheck;
            $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
        }
        if($routeParams.orderFlag){//是否交易    1 成交客户
            $scope.searchMap.orderFlag=$routeParams.orderFlag;
            $scope.config.orderFlag=$routeParams.orderFlag;
            $scope.config.showOrderFlag=true;
            $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
        }
        console.info($routeParams.systemUserId)
        if($routeParams.systemUserId){//当前用户ID  我的客户列表
            $scope.searchMap.systemUserId=$routeParams.systemUserId;
            $scope.config.systemUserId=$routeParams.systemUserId;
            //$scope.searchMap.systemUserId2=$routeParams.systemUserId;
            $scope.config.showSystemUser=true;
            $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
        }
        if($routeParams.pageNo){//当前用户ID  我的客户列表
            $scope.searchMap.pageNo=$routeParams.pageNo;
            $scope.config.pageNo=$routeParams.pageNo-0;
        }

        if(($routeParams.orderFlag==2&&$routeParams.notHasVisit)||$routeParams.orderFlag==1){
            $scope.showVisit=true;
            if($routeParams.orderFlag==2&&$routeParams.notHasVisit){
                $scope.showVisitWhere=true;
            }else{
                $scope.showVisitWhere=false;
            }
        }
    }

    $scope.config1 = {"pageSize": 10000};
    var sss = {"userId": "*", "username": "*无服务顾问*"};
    if (!$scope.config.showSystemUser) {
        licaishiManagerService.list($scope.config1).then(function (json) {
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.licaishiManagerUserList = json.list;
                $scope.licaishiManagerUserList.push(sss);
                $scope.loading = false;
            }
        });
    } else {
        licaishiManagerService.otherList($scope.config1).then(function (json) {
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.licaishiManagerUserList = json.list;
                $scope.licaishiManagerUserList.push(sss);
                $scope.loading = false;
            }
        });
    }


    $scope.chkAllLicaishiList = function () {
        if ($("#chkAllLicaishiList").attr("checked") == "checked") {
            $("[name='chkLicaishiList']").attr("checked", "checked");
        } else {
            $("[name='chkLicaishiList']").attr("checked", false);
        }
    }

    $scope.licaishiManage = function (t) {
        chooseLicaishiList(t);
        if ($scope.chooseLicaishiId != undefined && $scope.chooseLicaishiId != "") {
            $scope.chooseLicaishiIdCount = $scope.chooseLicaishiId.split(",").length - 1;
            $scope.isShowLicaishiManagerLayer = true;
        } else {
            alert("请选择理财师！");
            return;
        }
        if (t != undefined && t != "" && t == "1") {
            licaishiManagerService.list({"pageSize": 9999, "pageNo": 1}).then(function (json) {
                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    $scope.licaishiManagerUserList2 = json.list;
                }
            });
        }
        $scope.t = t;
    };
    chooseLicaishiList = function (t) {
        $scope.chooseLicaishiId = "";
        $scope.omu = "";
        $("[name='chkLicaishiList']").each(function (i) {
            if ($(this).attr("checked") == "checked") {
                //if(t == 1 && $(this).attr("omu")){
                //  alert("请选择未分配的理财师！");
                //  $scope.chooseLicaishiId = -1;
                //  return false;
                //}else
                if (t == 0 && !$(this).attr("omu")) {
                    alert("请选择已分配的理财师！");
                    $scope.chooseLicaishiId = -2;
                    return false;
                }
                if ($(this).attr("value") != undefined && $(this).attr("value") != "") {
                    $scope.chooseLicaishiId += $(this).attr("value") + ",";
                    $scope.omu += $(this).attr("omu") + ",";
                }
            }
        });
    };
    $scope.managerLicaishi = {};
    $scope.fenpeiOrHuishou = function (t) {
        if ($scope.chooseLicaishiId != null && $scope.chooseLicaishiId != undefined) {
            $scope.managerLicaishi.licaishiIds = $scope.chooseLicaishiId.substring(0, $scope.chooseLicaishiId.length - 1);
        }
        if (t == "1") {
            if ($scope.managerLicaishi.systemUserId != undefined && $scope.managerLicaishi.systemUserId != "" && t != "") {
                // 分配操作
                licaishiManagerService.managerLicaishiUserAdd($scope.managerLicaishi).then(function (json) {
                    if (json.statusCode) {
                        alert("出错了:" + json.statusCode);
                    } else {
                        // 操作成功！分配成功！
                        var _map = json.map;
                        if(_map.not_aCount>0){
                            alert('A类分配超出上限，失败'+_map.not_aCount);
                        }else if(_map.not_okCount>0){
                            alert('OK类分配超出上限，失败'+_map.not_okCount);
                        }else {
                            $scope.alertNextPage("分配成功！");
                        }



                        $route.reload();
                    }
                }, function (res) {
                    alert('网络状态不稳定或超时！');
                });
            } else {
                alert("请选择服务顾问！");
            }
        } else if (t == '0') {
            var tmpid = "";
            angular.forEach($scope.omu.split(","), function (o, i) {
                if (i == 0) {
                    tmpid = o;
                } else {
                    if (o != undefined && o != "" && o != tmpid) {
                        tmpid = "-99";
                    }
                }
            });
            if (tmpid != undefined && tmpid != "-99") {
                // 回收时，理财师服务顾问设为空
                $scope.managerLicaishi.systemUserId = "";
                // 回收
                licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function (json) {
                    if (json.statusCode) {
                        alert("出错了:" + json.statusCode);
                    } else {
                        $scope.alertNextPage("回收成功！");
                        $route.reload();
                    }
                });
            } else {
                if (confirm("选择了多个理财师，且服务顾问人不同，确认要同时回收吗！")) {
                    // 回收时，服务理财师设为空
                    $scope.managerLicaishi.systemUserId = "";
                    // 回收
                    licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function (json) {
                        if (json.statusCode == "4002") {
                            alert("存在已分配理财师，请先收回，后分配！");
                        } else if (json.statusCode) {
                            alert("出错了:" + json.statusCode);
                        } else {
                            $scope.alertNextPage("回收成功！");
                            $route.reload();
                        }
                    });
                }
            }
        }
    }

    $scope.config['orderBy'] = $routeParams.orderBy || '',
        $scope.config['orderByTag'] = $routeParams.orderByTag || '',

        $rootScope.viewNextBtn = {
            listWhere : $scope.listWhere

        }
    console.log($scope.config)
    $scope.$watch('config',function(){
        if ($scope.watchIsChange()){
            shopService.shopUserList($scope.config).then(function(json){
                $scope.fas = json.list || [];
                $scope.pager = json.pager;
                $rootScope.myKeHuNowPageListSize = json.list || [];
                $rootScope.viewNextBtn.pageNo = $scope.pager.pageNo;
                var arr = [];
                for(t in json.list){
                    arr.push(json.list[t].id);
                }
                $cookies.myKeHuNowPageListSize = angular.toJson(arr);
            });
        }
    },true);
    //读取查询 seeionStronge
    $scope.getLastSearchConfig();
    // $scope.search();

    $scope.orderbyPositionMap = {};
    if (!$routeParams.orderBy && !$routeParams.orderByTag) {
        $scope.orderbyPositionMap['weight'] = "0";
    } else {
        $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
    }
    $scope.orderbyFreqMap = {
        "createDate": ["desc", "asc"],
        "lastLoginTime": ["desc", "asc"],
        "latestVisitTime": ["desc", "asc"],
        "addAuthDate": ["desc", "asc"]
    };
    $scope.orderby = function (field) {
        var freq = $scope.orderbyFreqMap[field];
        var old = $scope.orderbyPositionMap[field];
        $scope.orderbyPositionMap = {};

        if (old == undefined) {
            $scope.orderbyPositionMap[field] = 0;
        } else {
            $scope.orderbyPositionMap[field] = old + 1;
            if ($scope.orderbyPositionMap[field] >= freq.length) {
                $scope.orderbyPositionMap[field] = 0;
            }
        }

        if (field == "weight") {
            $scope.config.orderBy = "";
            $scope.config.orderByTag = "";
        } else {
            $scope.config.orderBy = field;
            $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
        }
    }

    $scope.toViewPage = function (id) {
        var url = 'shop/faauit?id=' + id + $scope.listWhere + '&pageNo=' + $scope.config.pageNo;
        $location.url(url);
    }

    $scope.showBlackAddForm = function (id) {
        $scope.black.userId = id;
        $scope.showBlackAddFormFlag = true;
    };

    //$scope.blackAdd = function(){
    //    if (!$scope.form.$invalid){
    //        faService.blackAdd($scope.black).then(function(json){
    //            if (!json.statusCode){
    //                $scope.addAlert("操作成功");
    //                $route.reload();
    //            }else{
    //                alert("出错了:" + json.statusCode);
    //            }
    //        });
    //    }else{
    //        alert("请先完整填写信息");
    //        return;
    //    }
    //};

    $scope.cert = {id: ""};
    $scope.showCertForm = function (id) {
        $scope.cert.id = id;
        $scope.showCertFormFlag = true;

    };
    //$scope.certSave = function(){
    //    if (!$scope.certform.$invalid){
    //        if ($scope.cert.type && $scope.cert.uRole != "99"){
    //            $scope.cert.uRole = $scope.cert.type;
    //        }
    //        if (!$scope.cert.uRole || ($scope.cert.uRole == "2" && !$scope.cert.type)){
    //            alert("请选择评级");
    //            return;
    //        }
    //        faService.certSave($scope.cert).then(function(json){
    //            if (!json.statusCode){
    //                $scope.addAlert("操作成功");
    //                $route.reload();
    //            }else{
    //                alert("出错了:" + json.statusCode);
    //            }
    //        });
    //    }else{
    //        alert("请先完整填写信息");
    //        return;
    //    }
    //};

    $scope.selectLevelType = function (type) {
        $scope.cert.type = type;
        $scope.cert.uRole = "2";
    };

    $scope.selectRoleResult = function () {
        if ($scope.cert.uRole == "99") {
            $scope.cert.type = "";
        }
    }

    $scope.export = function () {
        exportService.exportCSV($scope.config, "faList_EXPORT");
    };


    $scope.setPageSize = $scope.config.pageSize;

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };
    if ($scope.dictMap.rzMapModel[0].value != 'Y') $scope.dictMap.rzMapModel;


}])

faApp.controller('ShopSucaiCtrl', ['$scope', 'shopService', '$location', '$rootScope', '$controller', '$route', '$routeParams', 'exportService', 'licaishiManagerService', 'sessionService', function ($scope, shopService, $location, $rootScope, $controller, $route, $routeParams, exportService, licaishiManagerService, sessionService) {
    var sucai = {}
    $scope.sucai = sucai;

    $scope.ctrlName = "ShopSucaiCtrl";
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.staticHost=App.staticHost;

    $scope.config['orderBy'] = $routeParams.orderBy || '',
        $scope.config['orderByTag'] = $routeParams.orderByTag || '',

        $scope.$watch('config', function () {
            if ($scope.watchIsChange()) {
                shopService.shopSucaiList($scope.config).then(function (json) {
                    $scope.fas = json.list || [];
                    $scope.pager = json.pager;
                    $rootScope.myKeHuNowPageListSize = json.list || []
                });
            }
        }, true);
    //读取查询 seeionStronge
    $scope.getLastSearchConfig();
    $scope.search();
}])
faApp.controller('ShopSucaiAddCtrl', ['$scope', 'shopService', '$location', '$rootScope', '$controller', '$route', '$routeParams', 'exportService', 'licaishiManagerService', 'sessionService', function ($scope, shopService, $location, $rootScope, $controller, $route, $routeParams, exportService, licaishiManagerService, sessionService) {
    $controller('BaseCtrl', {$scope: $scope});

    $scope.sucai = {"sucaiSort":10};
    $scope.loading = true;

    $scope.onUploadFile({
        showMessage : function(m){ alert(m); },
        onComplete:function(f,response){
            if (response.statusCode == "0000") {
                $scope.sucai.picAddre = App.staticHost + response.attribute.fileUrl;
                $scope.$apply();
            } else {
                alert('上传失败');
            }
        }
    });
}])

faApp.controller('ShopFaViewCtrl',['$rootScope','$scope','faService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,faService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $controller('BaseCtrl', {$scope: $scope});

    $scope.id = $routeParams.id;
    $scope.item = {};
    $scope.visit = {};
    $scope.loading = true;
    $scope.auditOptionMessage = "";
    $scope.aoMsg = false;
    $scope.firstReturnVisitCycle = "";
    $scope.stayAwayFromTheLastVisit = "";

    var myKeHuNow = angular.fromJson($cookies.myKeHuNowPageListSize);

    $scope.listWhere="?newPage=true";
    $scope.vtype="";
    if($routeParams.orderFlag=="1"&&$routeParams.notHasVisit){
        $scope.vtype="成交客户列表";
    }else if($routeParams.orderFlag=="2"&&$routeParams.notHasVisit){
        $scope.vtype="待沉寂理财师列表";
    }else if($routeParams.notHasVisit){
        $scope.vtype="待回访理财师列表";
    }else if($routeParams.notHasCheck){
        $scope.vtype="待审核理财师列表";
    }else if($routeParams.isnoManagerUserLicaishi){
        $scope.vtype="待分配理财师列表";
    }else{
        $scope.vtype="所有理财师列表";
    }
    if($routeParams.isnoManagerUserLicaishi){//待分配
        $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
    }
    if($routeParams.notHasVisit){//是否回访
        $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
    }
    if($routeParams.notHasCheck){//待审核
        $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
    }
    if($routeParams.orderFlag){//是否交易    1 成交客户
        $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
    }
    if($routeParams.systemUserId){//当前用户ID  我的客户列表
        $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
    }
    if($routeParams.pageNo){//当前用户ID  我的客户列表
        $scope.listWhere=$scope.listWhere+"&pageNo="+$routeParams.pageNo;
    }
    $scope.$watch('id',function(){
        for(m in myKeHuNow){
            if( myKeHuNow[m] == $scope.id ){
                $scope.now = m;
            }
        }
        faService.faShopQuery({id:$scope.id}).then(function(json){
            $scope.item = json.faUserInfo || {};
            $scope.loading = false;
            /**基本 属性**/
            if($scope.item.sourceCode =="")  $scope.item.sourceCode="--";
            if($scope.item.sourceLoginName =="")  $scope.item.uManagerId="--";
            // $scope.item.uManagerId = $scope.item.uManagerId=0 || "--";
            if($scope.item.uManagerId==0) $scope.item.uManagerId="--";


            console.info("认证信息：")
            console.info($scope.item)
            /**审核 属性**/
            $scope.cert.uCompanyName = $scope.item.uCompanyName || "";
            $scope.cert.uCompanyADD = $scope.item.uCompanyADD || "";
            $scope.cert.uJob = $scope.item.uJob || "";
            $scope.cert.uShopRole = $scope.item.uShopRole ;
            $scope.cert.type = $scope.cert.uShopRole;
            $scope.cert.uRealName = $scope.item.uRealName || "";
            $scope.cert.uCompany = $scope.item.uCompany || "";
            if($scope.item.faUserauth){
                $scope.cert.wechatNo = $scope.item.faUserauth.wechatNo || "";
            }
            if($scope.item.uShopRole!="99"){
                //$scope.cert.uShopRole ="2";
            }
            $scope.cert.uAuditOpinion=$scope.item.uAuditOpinion ;
            if($scope.item.uShopRole=="99"&&$scope.cert.uAuditOpinion!="注册手机号码与名片手机号码不一致"&&$scope.cert.uAuditOpinion!="未上传名片或上传名片与资质要求不符"){
                $scope.auditop.auditOptionMessage=$scope.cert.uAuditOpinion;
                $scope.cert.uAuditOpinion="3";
                $scope.aoMsg=true;
            }
            $scope.cert.uSex = $scope.item.uSex;
            $scope.cert.uEmail = $scope.item.uEmail || "";
            $scope.cert.auditRemarks = $scope.item.auditRemarks || "";
            $scope.cert.uCardType = $scope.item.uCardType || "";
        });
    },true)

    $scope.isShowVisitLayer = false;
    $scope.isShowCheckFaUser = true;
    $scope.visitList = [];

    $scope.cert = {};
    $scope.auditop={};
    $scope.certSave = function(){
        $scope.cert.id = $scope.id
        if (!$scope.certform.$invalid){
            //if ($scope.cert.type && $scope.cert.uShopRole != "99"){
            //    $scope.cert.uShopRole = $scope.cert.type;
            //}
            //if (!$scope.cert.uShopRole || ($scope.cert.uShopRole == "2" && !$scope.cert.type)){
            //    alert("请选择评级");
            //    return;
            //}
            if ($scope.cert.uShopRole=='2'||$scope.cert.uShopRole=='99'){
            } else {
                alert("请选择认证情况！");
                return;
            }
            //if($scope.aoMsg&&$scope.cert.uShopRole == 99){
            //    if(!$scope.auditop.auditOptionMessage){
            //        alert("请填写未通过原因！");
            //        return;
            //    }
            //    $scope.cert.uAuditOpinion = $scope.auditop.auditOptionMessage;
            //}
            faService.shopCertSave($scope.cert).then(function(json){
                if (!json.statusCode){
                    if($scope.isNewCompany && $scope.newCompanyName){
                        faService.sanfangAdd({tpcFullName: $scope.newCompanyName}).then(function(json){
                            console.log(json);
                        });
                    }

                    $scope.addAlert("操作成功");
                    alert("操作成功！")
                    $location.url("/shop/falist"+$scope.listWhere);
                }else{
                    alert("出错了:" + json.statusCode);
                }
            });
        }else{
            alert("请先完整填写信息");
            return;
        }
    };

    $scope.selectLevelType = function(type){
        $scope.cert.type = type;
        $scope.cert.uShopRole = "2";
    };
    $scope.selectCustomerLable = function(type){
        $scope.visit.customerLable = type;
    };
    $scope.selectRoleResult = function(){
        if ($scope.cert.uShopRole == "99"){
            $scope.cert.type = "1";
            $scope.cert.uAuditOpinion="";
        }else{
            $scope.cert.type = "";

        }
    };

    $scope.auditOption = function(){
        if($scope.cert.uAuditOpinion == "3"){
            $scope.aoMsg = true;
        }else{
            $scope.aoMsg = false;
        }
    };

    $scope.markFaUser = function(){
        if($scope.id){
            faService.markFaUser($scope.id).then(function(json){
                if (json.statusCode){
                    alert("出错了:" + json.statusCode);
                }else{
                    $scope.companyInvitationCode = json.cic;
                    alert("标记成功！");
                }
            });
        }else{
            alert("系统异常，请刷新页面重试！");
        }
    }
}]);

faApp.controller('BehaviorHomeCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $controller('BaseCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.data = null;

    function queryData(){
        shopService.getBehaviorHomeList({data:$scope.data}).then(function(json){
            console.info(json)
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{
                $scope.behaviorHomeList=json.list;

            }
        });
    }
    queryData();

    $scope.queryList = function(){
        queryData();
    }
}]);
faApp.controller('BehaviorProdCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $controller('BaseCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.data = null;

    function queryData(){
        shopService.getBehaviorProdList({data:$scope.data}).then(function(json){
            console.info(json)
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{
                $scope.behaviorProdList=json.list;

            }
        });
    }
    queryData();

    $scope.queryList = function(){
        queryData();
    }
}]);
faApp.controller('BehaviorCustCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $scope.loading = true;
    $scope.data = null;

    function queryData(){
        shopService.getBehaviorCustList({data:$scope.data}).then(function(json){
            console.info(json)
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{
                $scope.behaviorCustList=json.list;

            }
        });
    }
    queryData();

    $scope.queryList = function(){
        queryData();
    }
}]);
faApp.controller('BehaviorFpCtrl',['$rootScope','$scope','shopService','$location',
    '$controller','$routeParams','$route','$cookies'
    ,function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies) {

    $controller('BaseListCtrl', {$scope: $scope});

     $scope.list = [];
    $scope.loading = true;
    $scope.data = null;
    $scope.getIn = 1;
    var searchData = {}
    $scope.faName = null;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1,
        "data" :$scope.data,
        "getIn" :$scope.getIn,
        "faName" :$scope.faName
    }

    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        shopService.getBehaviorFpList($scope.config).then(function (json) {

            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{
                $scope.behaviorFpList=json.list;
                $scope.pager = json.pager;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);


    $scope.queryList = function(){
        $scope.config.getIn = $scope.getIn;
        $scope.config.data = $scope.data;
        $scope.config.faName = $scope.faName;
    }

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };
}]);
faApp.controller('BehaviorFooterMenuCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $controller('BaseCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.data = null;

    function queryData(){
        shopService.getBehaviorFooterMenuList({data:$scope.data}).then(function(json){
            console.info(json)
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{
                $scope.behaviorFooterMenuList=json.list;

            }
        });
    }
    queryData();

    $scope.queryList = function(){
        queryData();
    }
}]);

//店招列表
faApp.controller('ShopBackGroundList',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {
    $controller('BaseListCtrl', { $scope: $scope });
    $scope.loading = true;
    $scope.data = null;
    $scope.listOne =[];
    $scope.listTwo =[];
    shopService.getShopBackGroundList({data:$scope.data}).then(function(json){
        console.info(json)
        if (json.statusCode){
            alert("出错了:" + json.statusCode);
        }else{
            json.list;
            for(var i=0;i<json.list.length;i++){
                if(json.list[i].type==1 ){
                    $scope.listOne.push(json.list[i])
                }else{
                    $scope.listTwo.push(json.list[i])
                }
            }

        }
    });


    $scope.save = function(id,t,imgSrc){
        var src =""
        if(imgSrc!=undefined && imgSrc.length>0){
            src = imgSrc;
        }
        if(src.length<=0) {
            if (!confirm("确认删除吗？")) {
                return false;
            }
        }
        shopService.getShopBackGroundAdd({id:id,backgroudImg:src}).then(function(json){
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{

                if(src.length==0){
                    $("#"+t).attr('src','');
                }
                alert("成功");
                $route.reload();
            }
        });

    }

    $scope.getId = function(id){
        $("#getId").val(id);
    }

    $scope.onUploadFile({
        showMessage: function(m) { alert(m); },
        type:'shopBackground',
        onComplete: function(f, response, id) {
            id--;
            if (response.statusCode == "0000") {
                $("#"+id).attr('src',response.attribute.fileUrl);
                var getId=$("#getId").val();
                $scope.save(getId,id,response.attribute.fileUrl);
            } else {
                alert('上传失败');
            }
        }
    });


}]);



faApp.controller('ShopUserFeedBackList',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout) {

    $controller('BaseCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            shopService.getShopUserFeedBackList($scope.config).then(function (json) {

                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    $scope.list = json.list;
                    $scope.pager = json.pager;
                    $scope.loading = false;
                }
            });
        }
    },true);

    var phones="";
    $scope.showDiv = function(id, phone){

        $scope.showCon=true;
        phones = phone;
        shopService.getShopUserFeedBackList($scope.config).then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                // $scope.list = json.list;
                angular.forEach(json.list,function(o){
                    if(o.fpUserPhone==phone){
                        var html = "";
                        var backList = [];

                        backList = o.backList;
                        for(var k = 0;k<backList.length;k++){
                            if(backList[k].type==0){
                                html+="<div style='float: left;margin-top: 15px'>用户"+backList[k].fpUserPhone+"：</div><div style='float: left;width: 300px;text-align:left;word-break: break-all;word-wrap: break-word;margin-top: 15px;background-color: #F5F5F5 '>"+ backList[k].content+"</div>";
                            }else{
                                html+="<div style='float: right;margin-top: 15px;clear: both'>：客服</div><div style='float: right;width: 450px;text-align:right;word-break: break-all;word-wrap: break-word;margin-top: 15px;'>"+ backList[k].content+"</div>";
                            }
                        }
                        $("#showContent").html(html);
                        $("#showContent").scrollTop($('#showContent')[0].scrollHeight);
                    }
                });
            }
        });

    };

    var feedBack = {}
    $scope.feedBack = feedBack;
    feedBack.item = {}
    $scope.addFeeBack = function () {
        if(phones.length>0) {
            feedBack.item.fpUserPhone = phones;
        }
        feedBack.item.type='1';
        shopService.getShopUserFeedBackADD(feedBack.item).then(function(json){
            console.info(json)
            if (json.statusCode){
                alert("出错了:" + json.statusCode);
            }else{

                var list = $scope.list;
                for(var c =0;c<list.length;c++){
                    if(list[c].fpUserPhone==phones){
                        list[c].backList.push(feedBack.item);
                        list[c].content=feedBack.item.content;
                    }
                }

                $("#showContent").html($("#showContent").html()+
                    "<br/><div style='float: right;margin-top:15px;clear:both'>：客服</div><div style='width: 450px;float: right;text-align:right;word-break: break-all;word-wrap: break-word;margin-top:15px'>"+
                    feedBack.item.content+"</div>");
                feedBack.item = {}

            }
        });
    }
}]);
faApp.controller('ShopSubjectListCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 10,
        "pageNo" : 1
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        shopService.getShopSubjectList($scope.config).then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.list = json.list;
                for(var i=0; i<$scope.list.length; i++) {
                    $scope.list[i].answer = eval('('+$scope.list[i].answer+')')
                }
                $scope.pager = json.pager;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);


    //新增答题
    {
        $scope.showaddanswer = false;

        //初始化新增答案
        function initAddAanwer() {
            $scope.answerarr = [];
            var item = {};
            item.subno = 'A';
            $scope.answerarr.push(item);

            $scope.subjectitem = {};
        }

        //新增答案
        $scope.addAnswer = function(){
            if($scope.answerarr.length==26) {
                alert("不能添加更多了！");
                return false;
            }

            var item = {};
            item.subno = $filter('answeNum')($scope.answerarr.length+1);
            $scope.answerarr.push(item);
        }


        //删除答案
        $scope.delAnswer = function(id){
            if(confirm("确认删除吗？")) {
                $scope.answerarr.splice(id,1);

                for(var i=0; i<$scope.answerarr.length; i++) {
                    $scope.answerarr[i].subno = $filter('answeNum')(i+1);
                }
            }
        }

        //打开新增答案窗口
        $scope.addnewanswer = function(){
            $scope.showaddanswer = true;
            initAddAanwer();
        }

        //隐藏新增答案窗口
        $scope.hideaddans = function() {
            $scope.showaddanswer = false;
        }

        //设置正确答案
        $scope.setTrueAnswer = function(subno){
            $scope.subjectitem.trueAnswer = subno;
        }

        $scope.changePageSize = function () {
            if (!$scope.setPageSize) {
                alert('不为空且最大不超过1000');
                $scope.setPageSize = $scope.config.pageSize;
            } else {
                $scope.config.pageSize = $scope.setPageSize;
            }
        };

        //保存题目
        $scope.saveSub = function() {
            if(!$scope.subjectitem.content) {
                alert("请填写试题内容!");
                return false;
            }
            var issubconemp = false;
            for(var i=0; i<$scope.answerarr.length; i++) {
                if(!$scope.answerarr[i].subcon) {
                    issubconemp = true;
                    break;
                }
            }
            if(issubconemp) {
                alert("题目答案内容不能为空!");
                return false;
            }
            if(!$scope.subjectitem.trueAnswer) {
                alert("请设置正确答案!");
                return false;
            }

            if($scope.answerarr.length<2){
                alert("请至少设置两个答案");
                return false;
            }


            $scope.subjectitem.answer = $scope.answerarr;

            var subForm = {}
            subForm.content = $scope.subjectitem.content;
            subForm.trueAnswer = $scope.subjectitem.trueAnswer;
            subForm.answer = angular.toJson($scope.subjectitem.answer);




            if(!$scope.subjectitem.shopSubjectId) {
                shopService.addShopSubject(subForm).then(function (json) {
                    //console.info(json)
                    $scope.showaddanswer = false;
                    initSearchData()
                })
            } else {
                subForm.shopSubjectId = $scope.subjectitem.shopSubjectId;
                shopService.updateShopSubject(subForm).then(function (json) {
                    //console.info(json)
                    $scope.showaddanswer = false;
                    initSearchData()
                })
            }

        }
    }

    //编辑
    $scope.editsubans = function(d) {
        $scope.showaddanswer = true;
        $scope.subjectitem = {}
        $scope.subjectitem.shopSubjectId = angular.copy(d.shopSubjectId);
        $scope.subjectitem.content = angular.copy(d.content);
        $scope.subjectitem.trueAnswer =  angular.copy(d.trueAnswer);
        $scope.answerarr =  angular.copy(d.answer);
    }

    $scope.deletesubans = function(d) {
        if(confirm("确认删除吗？")) {
            var subForm = {};
            subForm.shopSubjectId = d.shopSubjectId;
            shopService.deleteShopSubject(subForm).then(function (json) {
                alert("删除成功！");
                initSearchData();
            })
        }
    }
}]);
faApp.controller('BehaviorCustregisterList',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 50,
        "pageNo" : 1,
        "getPt": $scope.getPt,
        "monthStart": $scope.monthStart,
        "monthEnd": $scope.monthEnd
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        $scope.loading = true;
        shopService.getCustregisterList($scope.config).then(function (json) {
            $scope.loading = false;
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.list = json.l;
                $scope.pager = json.pager;
                $scope.jcs = json.jcs;
                $scope.sfa = json.sfa;
                $scope.times = json.times;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };

    $scope.queryList = function () {
        $scope.config.getPt = $scope.getPt;
        $scope.config.monthStart = $scope.monthStart;
        $scope.config.monthEnd = $scope.monthEnd;
        $scope.config.pageNo = 1;
        initSearchData();
    }
}]);
faApp.controller('BehaviorCruxdataList',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1,
        "monthStart" : $scope.monthStart,
        "monthEnd" : $scope.monthEnd
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        shopService.getCruxdataList($scope.config).then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.list = json.list;
                $scope.pager = json.pager;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };

    $scope.queryList = function () {
        $scope.config.monthStart = $scope.monthStart;
        $scope.config.monthEnd = $scope.monthEnd;
        initSearchData();
    }

}]);

faApp.controller('ShopInformationAddCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseCtrl', {$scope: $scope});

    var information = {};
    $scope.information = information;
    information.item = {};

    //初始化
    information.item.type = '1';
    information.item.upStatus = '1';
    information.item.pushMeg = '2';

    $scope.minDate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm');

    //保存
    $scope.save = function () {
        if($scope.information.item.type=='3') {
            if(!information.item.hotImg) {
                return false;
            }
            if(!information.item.commentHeaderurl) {
                return false;
            }
        }
        if ($scope.form.$invalid){
            if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
            if($scope.information.item.type != '4') {
                if ($scope.form.birefDesc.$invalid) $scope.form.birefDesc.$dirty = true;
            }
            if ($scope.form.type.$invalid)$scope.form.type.$dirty = true;
            if($scope.information.item.type == '2') {
                if ($scope.form.articleLink.$invalid) $scope.form.articleLink.$dirty = true;
            }
            if($scope.information.item.type != '2') {
                if ($scope.form.content.$invalid) $scope.form.content.$dirty = true;
            }
            if($scope.information.item.type=='3') {
                if ($scope.form.commentName.$invalid) $scope.form.commentName.$dirty = true;
                // if ($scope.form.commentHeaderurl.$invalid) $scope.form.commentHeaderurl.$dirty = true;
                if ($scope.form.commentIdentity.$invalid) $scope.form.commentIdentity.$dirty = true;
                if ($scope.form.commentPosition.$invalid) $scope.form.commentPosition.$dirty = true;
                if ($scope.form.commentContent.$invalid) $scope.form.commentContent.$dirty = true;
            }
            if ($scope.form.pushMeg.$invalid)$scope.form.pushMeg.$dirty = true;
            if ($scope.form.upStatus.$invalid)$scope.form.upStatus.$dirty = true;
        }else {
            var subForm = {}
            subForm = angular.copy(information.item);
            if(subForm.preTime) {
                subForm.preTime += ":00";
            }

            shopService.getShopInformationAdd(subForm).then(function (json) {
                $location.path('/shop/information/list')
            })
        }
    }

    $scope.onUploadFile({
        showMessage : function(m){ alert(m); },
        onComplete:function(f,response, id){
            id--;
            if (response.statusCode == "0000") {
                if(id==0) {
                    information.item.hotImg = App.staticHost + response.attribute.fileUrl;
                } else if(id==1) {
                    information.item.commentHeaderurl = App.staticHost + response.attribute.fileUrl;
                }
                $scope.$apply();
            } else {
                alert('上传失败');
            }
        }
    });

}]);
faApp.controller('ShopInformationEditCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseCtrl', {$scope: $scope});

    var id = $routeParams.id;
    console.info(id)

    var information = {};
    $scope.information = information;
    information.item = {};
    information.item.id = id;

    $scope.minDate = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm');

    if(id) {
        shopService.getShopInformationDetail(id).then(function (json) {
            information.item = json.dto;
            information.item.preTime = $filter('date')(information.item.preTime, "yyyy-MM-dd HH:mm");
        })
    }

    //保存
    $scope.save = function () {
        if ($scope.form.$invalid){
            if ($scope.form.title.$invalid)$scope.form.title.$dirty = true;
            if($scope.information.item.type != '4') {
                if ($scope.form.birefDesc.$invalid) $scope.form.birefDesc.$dirty = true;
            }
            if ($scope.form.type.$invalid)$scope.form.type.$dirty = true;
            if($scope.information.item.type == '2') {
                if ($scope.form.articleLink.$invalid) $scope.form.articleLink.$dirty = true;
            }
            if($scope.information.item.type != '2') {
                if ($scope.form.content.$invalid) $scope.form.content.$dirty = true;
            }
            if($scope.information.item.type=='3') {
                if ($scope.form.commentName.$invalid) $scope.form.commentName.$dirty = true;
                if ($scope.form.commentHeaderurl.$invalid) $scope.form.commentHeaderurl.$dirty = true;
                if ($scope.form.commentIdentity.$invalid) $scope.form.commentIdentity.$dirty = true;
                if ($scope.form.commentPosition.$invalid) $scope.form.commentPosition.$dirty = true;
                if ($scope.form.commentContent.$invalid) $scope.form.commentContent.$dirty = true;
            }
            if ($scope.form.pushMeg.$invalid)$scope.form.pushMeg.$dirty = true;
            if ($scope.form.upStatus.$invalid)$scope.form.upStatus.$dirty = true;
        }else {
            var subForm = {}
            subForm = angular.copy(information.item);
            subForm.releaseTime = $filter('date')(subForm.releaseTime, 'yyyy-MM-dd HH:mm:ss');
            if(subForm.preTime) {
                subForm.preTime += ":00";
            }

            shopService.getShopInformationEdit(subForm).then(function (json) {
                $location.path('/shop/information/list')
            })
        }
    }

    $scope.onUploadFile({
        showMessage : function(m){ alert(m); },
        onComplete:function(f,response,id){
            id--;
            if (response.statusCode == "0000") {
                if(id==0) {
                    information.item.hotImg = App.staticHost + response.attribute.fileUrl;
                } else if(id==1) {
                    information.item.commentHeaderurl = App.staticHost + response.attribute.fileUrl;
                }
                $scope.$apply();
            } else {
                alert('上传失败');
            }
        }
    });

}]);
faApp.controller('ShopInformationListCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1,
        "type": $scope.type,
        // "releaseTimeStart": $scope.releaseTimeStart
        // "releaseTimeEnd": $scope.releaseTimeEnd
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        shopService.getShopInformationList($scope.config).then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.list = json.list;
                $scope.pager = json.pager;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };

    //查询
    $scope.queryList = function () {
        $scope.config.type = $scope.type;
        // $scope.config.releaseTimeStart = $scope.releaseTimeStart;
        // $scope.config.releaseTimeEnd = $scope.releaseTimeEnd;
        initSearchData();
    }

    //删除
    $scope.deleteInformation= function(id){
        if(id){
            if(confirm('确定要删除吗！')){
                shopService.getShopInformationDelete({id: id}).then(function(json){
                    if (json.statusCode){
                        alert(json.statusCode);
                    }else{
                        $route.reload();
                    }
                });
            }
        }
    }

    //上下架
    $scope.upordownInfo = function (id, status) {
        var subForm = {}
        subForm.id = id;
        subForm.upStatus = status;

        shopService.upordownInformation(subForm).then(function (json) {
            alert("操作成功!");
            $route.reload();
        })
    }
}]);

faApp.controller('jcsYxtActivityCount',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});
    $scope.loading = true;
    $scope.config={
        'monthStart':$scope.monthStart,
        'monthEnd':$scope.monthEnd
    }
    var initSearchData =function () {
        shopService.jcsYxtActivityCount($scope.config).then(function (json) {
            console.log(json)
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.news = json.news;
                $scope.newsRole = json.newsRole;
                $scope.allIn = json.allIn;
            }
        });
    }
    initSearchData();

    $scope.search = function () {
        $scope.config.monthStart = $scope.monthStart;
        $scope.config.monthEnd = $scope.monthEnd;
        initSearchData();
    }

}]);
faApp.controller('jcsYxtActivityDrawCount',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.activityCode = 'JCSYXT';//默认查英雄帖活动
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1,
        "mobile":$scope.mobile,
        "activityCode":$scope.activityCode
    }
    var initSearchData =function () {
        shopService.jcsYxtActivityDrawCount($scope.config).then(function (json) {
            console.log(json)
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.all = json.all;
                $scope.list = json.news;
                $scope.now = json.now;
                $scope.pager = json.page;
            }
        });
    }
    initSearchData();

    $scope.search = function () {
        $scope.config.mobile = $scope.mobile;
        $scope.config.activityCode = $scope.activityCode;
        initSearchData();
    }

    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
        initSearchData();
    };
    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
            initSearchData();
        } else {
            $scope.config.pageSize = $scope.setPageSize;
            initSearchData();
        }
    };
}]);


faApp.controller('pcTotalDynamic',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});
    $scope.loading = true;

    $scope.save =function () {

        shopService.pcTotalDynamicUpdate({"allUser":$scope.total.allUser,"allCooperation":$scope.total.allCooperation,"allAmount":$scope.total.allAmount})
            .then(function (json) {
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                alert("修改成功")
            }

        });
    }


    var initSearchData =function () {
        shopService.pcTotalDynamic().then(function (json) {
            console.log(json)
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.allAmounts = json.allAmount;
                $scope.allUsers = json.allUser;
                $scope.total = json.dto;
            }
        });
    }
    initSearchData();

}]);



faApp.controller('playOpenApplyList',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});
    $scope.loading = true;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1
    }

    $scope.save =function (cg,id) {

        shopService.playOpenApplyEdit({"id":id,"qStatus":cg})
            .then(function (json) {
                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    alert("修改成功")
                    initSearchData()
                }

            });
    }


    var initSearchData =function () {
        shopService.playOpenApplyList($scope.config).then(function (json) {
            console.log(json)
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {

                $scope.list = json.list;
                $scope.pager = json.pager;
            }
        });
    }
    initSearchData();

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
        initSearchData();
    };
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
        initSearchData();
    };
    $scope.search = function () {

        $scope.config.qStatus = $scope.qStatus;
        initSearchData();
    }
}]);

faApp.controller('shopInfoListCtrl',['$rootScope','$scope','shopService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,shopService,$location,$controller,$routeParams,$route,$cookies,$timeout, $filter) {
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.list = [];
    $scope.loading = true;
    $scope.config={
        "pageSize" : 20,
        "pageNo" : 1,
        "deleteTag": '1',
        "shopPhone": $scope.shopPhone,
        "shopName": $scope.shopName
    }
    $scope.pageChanged = function(){
        $scope.config.pageNo = $scope.pager.pageNo;
    };

    function initSearchData() {
        shopService.getShopInfoList($scope.config).then(function (json) {

            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                $scope.list = json.list;
                $scope.pager = json.pager;

                $scope.setPageSize = $scope.pager.pageSize;
            }
        });
    }

    $scope.$watch('config',function(){
        if ($scope.watchIsChange()) {
            initSearchData();
        }
    },true);

    $scope.changePageSize = function () {
        if (!$scope.setPageSize) {
            alert('不为空且最大不超过1000');
            $scope.setPageSize = $scope.config.pageSize;
        } else {
            $scope.config.pageSize = $scope.setPageSize;
        }
    };

    //查询
    $scope.queryList = function () {
        $scope.config.shopPhone = $scope.shopPhone;
        $scope.config.shopName = $scope.shopName;
        initSearchData();
    }

    //新增
    $scope.showAddShopInfoWin = false;
    $scope.addOrEditShopInfo = function () {
        $scope.showAddShopInfoWin = true;
    }

    //删除
    $scope.deleteInformation= function(id){
        if(id){
            if(confirm('确定要删除吗！')){
                shopService.updateShopInfo({id: id, deleteTag: "2"}).then(function(json){
                    if (json.statusCode){
                        alert(json.statusCode);
                    }else{
                        $route.reload();
                    }
                });
            }
        }
    }

    $scope.editInformation= function(data){
        $scope.showAddShopInfoWin = true;
        $scope.item = data;
    }

    //保存
    $scope.item = {};
    $scope.shopInfoSave = function () {
        if($scope.item.id) {
            shopService.updateShopInfo($scope.item).then(function (json) {
                $scope.showAddShopInfoWin = false;
                alert('保存成功！');
                initSearchData();

                $scope.item = {};
            });
        } else {
            shopService.addShopInfo($scope.item).then(function (json) {
                $scope.showAddShopInfoWin = false;
                alert('保存成功！');
                initSearchData();

                $scope.item = {};
            });
        }
    }
}]);
faApp.controller('SimuListCtrl',['$scope','simuService','$location','$controller','$route',function($scope,simuService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;
 
  $scope.$watch('config',function(){
    simuService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };   

  $scope.searchMap = {
    "jjmc" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    $scope.config.pageNo = 1;

  };

  $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }
    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    simuService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id],fpProjectType:'01'}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };
  
  // $scope.remove = function(id){
  //   simuService.remove({id:id}).then(function(json){
  //     if (json.statusCode){
  //       alert("出错了:" + json.statusCode);
  //     }else{
  //       $route.reload();
  //     }
  //   });
  // };
  
 /* $scope.stop = function(id,jjbm){
    simuService.stop({id:id,jjbm:jjbm}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
  
  $scope.start = function(id,jjbm){
    simuService.start({id:id,jjbm:jjbm}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
};*/
}]);

faApp.controller('SimuBaseInfoCtrl',['$scope','$location','$controller','$routeParams','$timeout',function($scope,$location,$controller,$routeParams,$timeout) {   
  $controller('BaseCtrl', {$scope: $scope});
  $scope.id=$routeParams.id;
  $scope.jjbm=$routeParams.jjbm;
  $scope.pathText="产品详情";
  $scope.tabUrlMap = {
    viewUrl : "#/simu/view?id=" + $scope.id,
    baseUrl : "#/simu/edit?id=" + $scope.id,
    buyinfoUrl : "#/simu/buyinfo/edit?id=" + $scope.id + "&jjbm=" + $scope.jjbm,
    buythisUrl : "#/simu/buyhis/addlist?id=" + $scope.id+"&jjbm=" + $scope.jjbm,
    lsyjUrl : "#/simu/lsyj?id=" + $scope.id,
    ndyjUrl : "#/simu/ndyj?id=" + $scope.id,
    lsjzUrl : "#/simu/lsjz?id=" + $scope.id,
    spnrUrl : "#/simu/spnr?id="+$scope.id + "&jjbm=" + $scope.jjbm,
  };
  $scope.tabUrl={};
  $scope.changeTab = function(tab){
    var tmp = tab.split(",");
    for(var i=0;i<tmp.length;i++){
      $scope.tabUrl[tmp[i]] = $scope.tabUrlMap[tmp[i]];
    }
    //$scope.tabUrl['ndyjUrl'] = $scope.tabUrlMap['ndyjUrl'];
  };
  
  $scope.changeTab('viewUrl');
  
}]);

faApp.controller('SimuAddCtrl',['$scope','simuService','simuCompanyService','simuManagerService','$location','$controller','$timeout','$routeParams',function($scope,simuService,simuCompanyService,simuManagerService,$location,$controller,$timeout,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope});

  $scope.item = {};
  $scope.loading = true; 
  $scope.simuCompanyListing = [];
  $scope.simuCompanyListed = [];
  $scope.simuCurCompanyListed = [];
  $scope.companyKw = "";
  $scope.allTjzls = {};
  if($routeParams.outProductId!=undefined){
    $scope.item.outProductId=$routeParams.outProductId;
  }
  if($routeParams.productName!=undefined){
    $scope.item.jjqc=$routeParams.productName;
    $scope.item.jjmc=$routeParams.productName;
    
  }
  $scope.$watch('companyKw',function(){
    $scope.companyKw = $scope.companyKw.trim();
    if ($scope.companyKw){
      simuCompanyService.list({pageSize:20,pageNo:1,gsmc:$scope.companyKw}).then(function(json){
        $scope.simuCompanyListing = json.list;
      });
    }else{
      $scope.simuCompanyListing = [];
    }
  });
  
  $scope.selectCompany = function(id,idx,isCur){
    angular.forEach($scope.simuCompanyListing,function(o){
      if (o.id == id){
        var existFlag = false;
        angular.forEach($scope.simuCompanyListed,function(oo){
          if (oo.id == id)existFlag = true;
        });
        if (!existFlag) {
          if (isCur){
            $scope.simuCurCompanyListed = [o];
            $scope.item.jjgsId = o.id;
            $scope.item.jjgs = o.gsmc;
          }else{
            $scope.simuCompanyListed.push(o);
          }
        }
      }
    });
  };
  
  $scope.unSelectCompany = function(id,idx,isCur){
    if (isCur){
      $scope.simuCurCompanyListed = [];
      $scope.item.jjgsId = "";
      $scope.item.jjgs = "";
    }else{
      $scope.simuCompanyListed.splice(idx,1);
    }
  };
  

  $scope.simuManagerListing = [];
  $scope.simuManagerListed1 = [];
  $scope.simuManagerListed2 = [];
  $scope.managerKw = "";
  
  $scope.$watch('managerKw',function(){
    $scope.managerKw = $scope.managerKw.trim();
    if ($scope.managerKw){
      simuManagerService.list({pageSize:20,pageNo:1,jjjlmc:$scope.managerKw}).then(function(json){
        $scope.simuManagerListing = json.list;
      });
    }else{
      $scope.simuManagerListing = [];
    }
  });
  
  $scope.selectManager = function(id,idx,isCur){
    angular.forEach($scope.simuManagerListing,function(o){
      if (o.id == id){ 
        if (isCur){
          $scope.simuManagerListed1 = [o];
          $scope.item.jjjlbm = o.jjjlbm;
        }else{
          $scope.simuManagerListed2 = [o];
          $scope.item.jjjlbm2 = o.jjjlbm;
        } 
      }
    });
  };
  
  $scope.unSelectManager = function(id,idx,isCur){
    if (isCur){
      $scope.simuManagerListed1 = [];
      $scope.item.jjjlbm = "";
    }else{
      $scope.simuManagerListed2 = [];
      $scope.item.jjjlbm2 = "";
    }
  };

  $scope.getJJBM=function(){
    // var v;
    // if($scope.item.jjfl=='股票型'){
    //   v="GP";
    // }else if($scope.item.jjfl=='债券型'){
    //   v="ZJ";
    // }else if($scope.item.jjfl=='期货型'){
    //   v="QH";
    // }else if($scope.item.jjfl=='混合型'){
    //   v="HH";
    // }else{
    //   v="QT";
    // }
    // if(v!=undefined){
    simuService.queryjjbm().then(function(json){
       $scope.item.jjbm=json.code;
    });
    // }
  };
  $scope.getJJBM();
  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else if($scope.simuCurCompanyListed==""||$scope.simuManagerListed1==""){
      alert("基金公司和基金经理必填");
      return;
    }else{
      $scope.selectTjzls = [];
     var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.item.tjzls=$scope.selectTjzls.join(",");
      if ($scope.item.jjclsjstr){$scope.item.jjclsj = $scope.item.jjclsjstr + " 00:00:00";}
      simuService.add($scope.item).then(function(json){
        if (json.statusCode){
          if(json.statusCode=='2003'){
            alert("基金编码重复");
          }else{
            alert("报错了:"+json.statusCode);
          }
        }else{
          $location.path("/simu/list");
        }
      });
    }
  }; 

}]);

faApp.controller('SimuEditCtrl',['$scope','simuCompanyService','simuManagerService','simuService','$location','$controller','$routeParams','$route','$filter',function($scope,simuCompanyService,simuManagerService,simuService,$location,$controller,$routeParams,$route,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;
  $scope.simuCompanyListing = [];
  $scope.simuCompanyListed = [];
  $scope.simuCurCompanyListed = [];
  $scope.companyKw = "";
  $scope.allTjzls = {};
  
  $scope.$watch('companyKw',function(){
    $scope.companyKw = $scope.companyKw.trim();
    if ($scope.companyKw){
      simuCompanyService.list({pageSize:20,pageNo:1,gsmc:$scope.companyKw}).then(function(json){
        $scope.simuCompanyListing = json.list;
      });
    }else{
      $scope.simuCompanyListing = [];
    }
  });
  
  $scope.selectCompany = function(id,idx,isCur){
    angular.forEach($scope.simuCompanyListing,function(o){
      if (o.id == id){
        var existFlag = false;
        angular.forEach($scope.simuCompanyListed,function(oo){
          if (oo.id == id)existFlag = true;
        });
        if (!existFlag) {
          if (isCur){
            $scope.simuCurCompanyListed = [o];
            $scope.item.jjgsId = o.id;
            $scope.item.jjgs = o.gsmc;
          }else{
            $scope.simuCompanyListed.push(o);
          }
        }
      }
    });
  };
  
  $scope.unSelectCompany = function(id,idx,isCur){
    if (isCur){
      $scope.simuCurCompanyListed = [];
      $scope.item.jjgsId = "";
      $scope.item.jjgs = "";
    }else{
      $scope.simuCompanyListed.splice(idx,1);
    }
  };
  

  $scope.simuManagerListing = [];
  $scope.simuManagerListed1 = [];
  $scope.simuManagerListed2 = [];
  $scope.managerKw = "";
  
  $scope.$watch('managerKw',function(){
    $scope.managerKw = $scope.managerKw.trim();
    if ($scope.managerKw){
      simuManagerService.list({pageSize:20,pageNo:1,jjjlmc:$scope.managerKw}).then(function(json){
        $scope.simuManagerListing = json.list;
      });
    }else{
      $scope.simuManagerListing = [];
    }
  });
  
  $scope.selectManager = function(id,idx,isCur){
    angular.forEach($scope.simuManagerListing,function(o){
      if (o.id == id){ 
        if (isCur){
          $scope.simuManagerListed1 = [o];
          $scope.item.jjjlbm = o.jjjlbm;
        }else{
          $scope.simuManagerListed2 = [o];
          $scope.item.jjjlbm2 = o.jjjlbm;
        } 
      }
    });
  };
  
  $scope.unSelectManager = function(id,idx,isCur){
    if (isCur){
      $scope.simuManagerListed1 = [];
      $scope.item.jjjlbm = "";
    }else{
      $scope.simuManagerListed2 = [];
      $scope.item.jjjlbm2 = "";
    }
  };

  simuService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail || {};
    $scope.item.zdrgje=parseInt($scope.item.zdrgje);
    $scope.item.zjzdje=parseInt($scope.item.zjzdje);
    $scope.item.jjclsjstr = $filter("date")($scope.item.jjclsj,"yyyy-MM-dd");
    $scope.simuCurCompanyListed = [json.company];
    if (json.manager && json.manager.jjjlmc)$scope.simuManagerListed1 = [json.manager];
    if (json.manager && json.manager.jjjlmc)$scope.simuManagerListed2 = [json.manager2];
    delete $scope.item.jjclsj;
    delete $scope.item.lsjzJson;
    delete $scope.item.lsyjbJson;
    delete $scope.item.ndyjbJson;
    if($scope.item.tjzls!=undefined){
      angular.forEach($scope.item.tjzls.split(","),function(o){
        $scope.allTjzls[o] = true;  
      }); 
    }
    $scope.loading = false;
  });

  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
    }else if($scope.simuCurCompanyListed==""||$scope.simuManagerListed1==""){
      alert("基金公司和基金经理必填");
      return;
    }else{
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.item.tjzls=$scope.selectTjzls.join(",");
      if ($scope.item.jjclsjstr){
        $scope.item.jjclsj = $scope.item.jjclsjstr + " 00:00:00";
      }else{
        $scope.item.jjclsj = "";
      }
      delete $scope.item.fpFundBuynoticeDTO;
      simuService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert(json.statusCode);
        }else{
          // $location.path("/simu/list");
          alert("修改成功");
          $route.reload();
        }
      });
    } 
  };


}]);

faApp.controller('SimuViewCtrl',['$scope','simuService','productService','userService','$location','$controller','$route','$routeParams','$sce',function($scope,simuService,productService,userService,$location,$controller,$route,$routeParams,$sce) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.userList = [];
    userService.userList().then(function(json){
      $scope.userRawList = json.list || [];
      angular.forEach($scope.userRawList,function(o){
        if (o.userNickname != $scope.loginStatus.loginName){
          $scope.userList.push(o);
        }
    });
  });
  $scope.transList = [];
  productService.transPermissionList({pProjectId:$scope.id,pProjectType:'02',pageSize:1000}).then(function(json){
    $scope.transList = json.list || [];
  });

  simuService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail || {};
    $scope.company = json.company|| {};
    $scope.manager = json.manager || {};
    $scope.manager2 = json.manager2 || {};
    //前台html展示
    $scope.item.fpFundBuynoticeDTO.buyNoticeDetail=$sce.trustAsHtml($scope.item.fpFundBuynoticeDTO.buyNoticeDetail);
    var zdf=angular.fromJson(App.filterSimuJson(json.detail.lsjzJson || "[]"));
    $scope.item.lsjz=zdf[0]||{};
    $scope.loading = false;
  });
  $scope.stop = function(id,jjbm){
    simuService.stop({id:id,jjbm:jjbm}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
  
  $scope.start = function(id,jjbm){
    simuService.start({id:id,jjbm:jjbm}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };

  $scope.remove = function(id){
    simuService.remove({id:id}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $location.path("/simu/list");
      }
    });
  };

  $scope.saveTrans = function(){
    if(!$scope.form.$invalid){
      $scope.trans.pProjectId=$scope.id;
      $scope.trans.pProjectType='02';
      productService.transPermissionAdd($scope.trans).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");
          parent.location.href = parent.location.href;
          //$route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };

}]);

faApp.controller('SimuBuyHisListCtrl',['$scope','simuBuyHisService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyHisService,simuService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope});  
  $scope.jjbm = $routeParams.jjbm;
  if (!$scope.jjbm){
    $location.path("/simu/list");
    return;
  }

  $scope.list = [];
  $scope.loading = true;
  $scope.jj = [];
  
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
  });

	$scope.$watch('config',function(){
    simuBuyHisService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
    "jjbm" : $routeParams.jjbm || "",
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  $scope.remove = function(id){
    simuBuyHisService.remove(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
}]);

faApp.controller('SimuBuyHisAddCtrl',['$scope','simuBuyHisService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyHisService,simuService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.jjbm = $routeParams.jjbm;
  if (!$scope.jjbm){
    $location.path("/simu/list");
    return;
  }

  $scope.item = {};
  $scope.loading = true;
  $scope.jj = [];
  
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
    $scope.item.jjbm = $scope.jj.jjbm;
    $scope.item.jjmc = $scope.jj.jjmc;
  }); 
  
  $scope.save = function(){
    if (!$scope.form.$invalid){
      simuBuyHisService.add($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $location.path("/simu/buyhis/list").search({jjbm:$scope.item.jjbm});
        }
      });
      
    }else{
      alert("请先完整填写表单");
    }
  };

}]);

faApp.controller('SimuBuyHisEditCtrl',['$scope','simuBuyHisService','$location','$controller','$route','$routeParams',function($scope,simuBuyHisService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.id = $routeParams.id;
  $scope.loading = true;

  simuBuyHisService.query($scope.id).then(function(json){
    $scope.item = json.detail;
    $scope.loading = false;
  });
  
  $scope.save = function(){
    if (!$scope.form.$invalid){
      simuBuyHisService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $location.path("/simu/buyhis/list").search({jjbm:$scope.item.jjbm});
        }
      });
      
    }else{
      alert("请先完整填写表单");
    }
  };

}]);

faApp.controller('SimuBuyHisViewCtrl',['$scope','simuBuyHisService','$location','$controller','$route',function($scope,simuBuyHisService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    simuBuyHisService.adList($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
}]);

faApp.controller('SimuBuyHisNewCtrl',['$scope','simuBuyHisService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyHisService,simuService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope});
  $scope.jjbm = $routeParams.jjbm;
  if (!$scope.jjbm){
    $location.path("/simu/list");
    return;
  }
  $scope.list = [];
  $scope.loading = true;
  $scope.jj = [];
  $scope.createBy='';
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
    $scope.createBy=$scope.jj.createBy;
  });

  $scope.$watch('config',function(){
    simuBuyHisService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "jjbm" : $routeParams.jjbm || "",
  };
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  }; 
  
  $scope.remove = function(id){
    simuBuyHisService.remove(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item={
      "id":$scope.list[v]['id'],
      "jjmc":$scope.list[v]['jjmc'],
      "gpdm":$scope.list[v]['gpdm'],
      "gpjc":$scope.list[v]['gpjc'],
      "cgs":$scope.list[v]['cgs'],
      "zltgbl":$scope.list[v]['zltgbl'],
      "cgbd":$scope.list[v]['cgbd'],
      "bdgs":$scope.list[v]['bdgs'],
      "bdbl":$scope.list[v]['bdbl'],
      "jzrq":$scope.list[v]['jzrq'],
    };
  };
  
  $scope.save = function(){
    $scope.item.jjbm = $scope.jj.jjbm;
    $scope.item.jjmc = $scope.jj.jjmc;
    if (!$scope.form.$invalid){
      if($scope.item.id==undefined){
        //新增操作
       simuBuyHisService.add($scope.item).then(function(json){
              if (json.statusCode){
                alert("出错了:" + json.statusCode);
              }else{
                $route.reload();
              }
        });
      }else{
        //编辑操作
        simuBuyHisService.edit($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $route.reload();
          }
        });
      }
    }else{
      alert("请先完整填写表单");
    }

  };
  

}]);





faApp.controller('SimuBuyInfoListCtrl',['$scope','simuBuyInfoService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyInfoService,simuService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.jjbm = $routeParams.jjbm;
  if (!$scope.jjbm){
    $location.path("/simu/list");
    return;
  }
  

  $scope.list = [];
  $scope.loading = true;
  $scope.jj = [];
  
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
    $scope.item.createBy = $scope.jj.createBy;
  });

	$scope.$watch('config',function(){
    simuBuyInfoService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
    "jjbm" : $routeParams.jjbm || "",
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 

  $scope.remove = function(id){
    simuBuyInfoService.remove(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
}]);

faApp.controller('SimuBuyInfoAddCtrl',['$scope','simuBuyInfoService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyInfoService,simuService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.jjbm = $routeParams.jjbm;
  if (!$scope.jjbm){
    $location.path("/simu/list");
    return;
  }

  $scope.item = {};
  $scope.loading = true;
  $scope.jj = [];
  
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
    $scope.item.jjbm = $scope.jj.jjbm;
    $scope.item.jjmc = $scope.jj.jjmc;
  }); 
  
  $scope.save = function(){
    if (!$scope.form.$invalid){
      simuBuyInfoService.add($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $location.path("/simu/buyinfo/list").search({jjbm:$scope.item.jjbm});
        }
      });
      
    }else{
      alert("请先完整填写表单");
    }
  };

}]);

faApp.controller('SimuBuyInfoEditCtrl',['$scope','simuBuyInfoService','simuService','$location','$controller','$route','$routeParams',function($scope,simuBuyInfoService,simuService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.item = {};
  $scope.id = $routeParams.id;
  $scope.jjbm = $routeParams.jjbm;
  $scope.loading = true;
  $scope.jj = [];
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail; 
  }); 
  simuBuyInfoService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.item = json.detail||{};
    if($scope.item.buyNoticeDetail==undefined||$scope.item.buyNoticeDetail==''){
      //style='font-family: 微软雅黑;font-size: 16px;'
       $scope.item.buyNoticeDetail = "<p class='p-c-title'><span ><a name='rgfl'></a>认购费率：</span></p><p class='p-c-title'><span ><a name='glfl'></a>管理费率：</span></p><p class='p-c-title'><span ><a name='shfl'></a>赎回费率：</span></p><p class='p-c-title'><span ><a name='tgfl'></a>托管费率：</span></p><p class='p-c-title'><span ><a name='yjfc'></a>业绩分成：</span></p><p class='p-c-title'><span ><a name='shsm'></a>赎回说明：</span></p>";
    }
    $scope.loading = false; 
  });
  $scope.save = function(){
    if (!$scope.form.$invalid){
      $scope.item.jjbm = $scope.jj.jjbm;
      $scope.item.jjmc = $scope.jj.jjmc;
      simuBuyInfoService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("修改成功");
          $route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
}]);

faApp.controller('SimuBuyInfoViewCtrl',['$scope','simuBuyInfoService','$location','$controller','$route','$routeParams',function($scope,simuBuyInfoService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.id = $routeParams.id;
  $scope.loading = true;

  simuBuyInfoService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail;
    $scope.loading = false;
  });

  $scope.remove = function(id){
    simuBuyInfoService.remove(id).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };

}]);






faApp.controller('SimuCompanyListCtrl',['$scope','simuCompanyService','$location','$controller','$route',function($scope,simuCompanyService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    simuCompanyService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};

  $scope.searchMap = {
		"gsmc" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  
  $scope.remove = function(id){
    simuCompanyService.remove({id:id}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
}]);

faApp.controller('SimuCompanyAddCtrl',['$scope','simuCompanyService','simuService','$location','$controller','$route',function($scope,simuCompanyService,simuService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {}; 
   $scope.getJJBM=function(){
    simuService.queryjjbm({"type":"GS","digit":"5"}).then(function(json){
       $scope.item.jjgsbm=json.code;
    });
  };
  $scope.getJJBM();
  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先正确填写表单");
      return;
    }else{
      if ($scope.item.clrqstr)$scope.item.clrq = $scope.item.clrqstr + " 00:00:00";
      simuCompanyService.add($scope.item).then(function(json){
        if (json.statusCode){
          if(json.statusCode=='2003'){
            alert("公司编码重复");
          }else{
           alert("出错了:" + json.statusCode);
          }
        }else{
          $location.path("/simu/company/list");
        }
      });
    }
  };
  
}]);

faApp.controller('SimuCompanyEditCtrl',['$scope','simuCompanyService','$location','$controller','$route','$routeParams','$filter',function($scope,simuCompanyService,$location,$controller,$route,$routeParams,$filter) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true;
  $scope.id = $routeParams.id;

  simuCompanyService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail;
    $scope.item.clrqstr = $filter("date")($scope.item.clrq,"yyyy-MM-dd");
    delete $scope.item.clrq;
    $scope.loading = false;
  });
  
  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先正确填写表单");
      return;
    }else{
      if ($scope.item.clrqstr)$scope.item.clrq = $scope.item.clrqstr + " 00:00:00";
      simuCompanyService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $location.path("/simu/company/list");
        }
      });
    }
  };
}]);

faApp.controller('SimuCompanyViewCtrl',['$scope','$sce','simuCompanyService','$location','$controller','$route','$routeParams',function($scope,$sce,simuCompanyService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = [];
  $scope.loading = true;
  $scope.id = $routeParams.id;
  
  simuCompanyService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail;
    //前台html展示
    $scope.item.tdjj=$sce.trustAsHtml($scope.item.tdjj);
    $scope.item.investIdea=$sce.trustAsHtml($scope.item.investIdea);
    $scope.item.investTeam=$sce.trustAsHtml($scope.item.investTeam);

  });

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  $scope.remove = function(id){
    simuCompanyService.remove({id:id}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $location.path("/simu/company/list");
      }
    });
  };
}]);






faApp.controller('SimuLsjzCtrl',['$scope','simuService','simuLsjzService','$location','$controller','$routeParams','$filter',function($scope,simuService,simuLsjzService,$location,$controller,$routeParams,$filter) {   
   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.formData = {id:$scope.id};
  $scope.item = {};
  $scope.jj = {};
  $scope.list = [];

  $scope.loading = true; 
  simuService.query({id:$scope.id}).then(function(json){
    $scope.jj = json.detail;
    json.detail.lsjzJson = App.filterSimuJson(json.detail.lsjzJson || "[]");
    $scope.list = angular.fromJson(json.detail.lsjzJson);
    $scope.formData.jjbm = $scope.jj.jjbm;
    $scope.item.createBy= $scope.jj.createBy;
  }); 

  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item = $scope.list[v];
  };

  $scope.deleteItem = function(v){
    $scope.list.splice(v,1);
    if (v > $scope.itemIndex){
      $scope.itemIndex --;
    }
    $scope.save(true);
  };

  $scope.save = function(deleteFlag){
    if (!deleteFlag){
      var v = $scope.itemIndex;
      if (v == undefined){
        $scope.list.unshift($scope.item);
      }else{
        $scope.list[v] = $scope.item;
      }
    }
    
    $scope.jj.lsjzJson = angular.toJson($scope.list);
    $scope.formData.lsjzJson = angular.toJson($scope.list);
    simuLsjzService.edit($scope.formData).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.addAlert("操作成功");
        $scope.item = {};
        $scope.itemIndex = undefined;
      }
    });
  };
 
}]);

faApp.controller('SimuLsyjCtrl',['$scope','simuService','simuLsyjService','$location','$controller','$routeParams','$filter',function($scope,simuService,simuLsyjService,$location,$controller,$routeParams,$filter) {   
   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.formData = {id:$scope.id};
  $scope.item = {};
  $scope.jj = {};
  $scope.list = [];

  $scope.loading = true; 
  simuService.query({id:$scope.id}).then(function(json){
    $scope.jj = json.detail;
    json.detail.lsyjbJson= App.filterSimuJson(json.detail.lsyjbJson) || "{}";
    $scope.list = angular.fromJson(json.detail.lsyjbJson);
    if ($scope.list.length != undefined)$scope.list = {};
    $scope.list["1"] = $scope.list["1"] || {"tjzq":"今年以来"};
    $scope.list["2"] = $scope.list["2"] || {"tjzq":"近一月"};
    $scope.list["3"] = $scope.list["3"] || {"tjzq":"近三月"};
    $scope.list["4"] = $scope.list["4"] || {"tjzq":"近六月"};
    $scope.list["5"] = $scope.list["5"] || {"tjzq":"近一年"};
    $scope.list["6"] = $scope.list["6"] || {"tjzq":"近两年"};
    $scope.list["7"] = $scope.list["7"] || {"tjzq":"近三年"};
    $scope.list["8"] = $scope.list["8"] || {"tjzq":"近五年"};
    $scope.list["9"] = $scope.list["9"] || {"tjzq":"成立以来"};
    
    $scope.formData.jjbm = $scope.jj.jjbm;
    $scope.edit(1);
    $scope.item.createBy = $scope.jj.createBy;
  }); 

  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item = $scope.list[v];
  };

  $scope.save = function(deleteFlag){ 
    $scope.jj.lsyjbJson = angular.toJson($scope.list);
    $scope.formData.lsyjbJson = angular.toJson($scope.list);
    simuLsyjService.edit($scope.formData).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.addAlert("操作成功");
        $scope.item = {};
        $scope.itemIndex = undefined;
      }
    });
  };
 
}]);

faApp.controller('SimuManagerListCtrl',['$scope','simuManagerService','$location','$controller','$route',function($scope,simuManagerService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;

	$scope.$watch('config',function(){
    simuManagerService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.pager;
      $scope.loading = false;
    });
  },true)

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};

  $scope.searchMap = {
		"gsmc" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  
  $scope.remove = function(id){
    simuManagerService.remove({id:id}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $route.reload();
      }
    });
  };
}]);

faApp.controller('SimuManagerAddCtrl',['$scope','simuCompanyService','simuManagerService','simuService','$location','$controller','$route',function($scope,simuCompanyService,simuManagerService,simuService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {}; 
  $scope.simuCompanyListing = [];
  $scope.simuCompanyListed = [];
  $scope.companyKw = "";
  
  $scope.$watch('companyKw',function(){
    $scope.companyKw = $scope.companyKw.trim();
    if ($scope.companyKw){
      simuCompanyService.list({pageSize:20,pageNo:1,gsmc:$scope.companyKw}).then(function(json){
        $scope.simuCompanyListing = json.list;
      });
    }else{
      $scope.simuCompanyListing = [];
    }
  });
  
  
  $scope.selectCompany = function(id,idx,isCur){
    angular.forEach($scope.simuCompanyListing,function(o){
      if (o.id == id){
        var existFlag = false;
        angular.forEach($scope.simuCompanyListed,function(oo){
          if (oo.id == id)existFlag = true;
        });
        if (!existFlag) {
          if (isCur){
            $scope.simuCurCompanyListed = [o];
            $scope.item.nowJjgsId = id;
            $scope.item.dqgzdsmjjgs = o.gsmc;
          }else{
            $scope.simuCompanyListed.push(o);
          }
        }
      }
    });
  };
  
  $scope.unSelectCompany = function(id,idx,isCur){
    if (isCur){
      $scope.simuCurCompanyListed = [];
      $scope.item.nowJjgsId = "";
      $scope.item.dqgzdsmjjgs = "";
    }else{
      $scope.simuCompanyListed.splice(idx,1);
    }
  }; 

   $scope.getJJBM=function(){
    simuService.queryjjbm({"type":"JL","digit":"5"}).then(function(json){
       $scope.item.jjjlbm=json.code;
    });
  };

  $scope.getJJBM();
  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先正确填写表单");
      return;
    }else{
      if($scope.simuCompanyListed.length){
        $scope.item.beforeJjgsIds = $scope.item.beforeJjgsIds || "";
        var beforeJjgsIdsList = $scope.item.beforeJjgsIds.split(",");
        angular.forEach($scope.simuCompanyListed,function(o){
          beforeJjgsIdsList.push(o.id);
        });
        $scope.item.beforeJjgsIds = beforeJjgsIdsList.join(",").trim(",");
      }
      simuManagerService.add($scope.item).then(function(json){
        if (json.statusCode){
          if(json.statusCode=='2003'){
            alert("经理编码重复");
          }else{
           alert("出错了:" + json.statusCode);
          }
        }else{
          $location.path("/simu/manager/list");
        }
      });
    }
  };
   $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.jlzpdz = response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  }); 
   

}]);

faApp.controller('SimuManagerEditCtrl',['$scope','simuCompanyService','simuManagerService','$location','$controller','$route','$routeParams',function($scope,simuCompanyService,simuManagerService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true;
  $scope.id = $routeParams.id;
  $scope.simuCompanyListing = [];
  $scope.simuCompanyListed = [];
  $scope.simuCurCompanyListed = [];
  $scope.companyKw = "";
  
  $scope.$watch('companyKw',function(){
    $scope.companyKw = $scope.companyKw.trim();
    if ($scope.companyKw){
      simuCompanyService.list({pageSize:20,pageNo:1,gsmc:$scope.companyKw}).then(function(json){
        $scope.simuCompanyListing = json.list;
      });
    }else{
      $scope.simuCompanyListing = [];
    }
  });
  
  $scope.selectCompany = function(id,idx,isCur){
    angular.forEach($scope.simuCompanyListing,function(o){
      if (o.id == id){
        var existFlag = false;
        angular.forEach($scope.simuCompanyListed,function(oo){
          if (oo.id == id)existFlag = true;
        });
        if (!existFlag) {
          if (isCur){
            $scope.simuCurCompanyListed = [o];
            $scope.item.nowJjgsId = id;
            $scope.item.dqgzdsmjjgs = o.gsmc;
          }else{
            $scope.simuCompanyListed.push(o);
          }
        }
      }
    });
  };
  
  $scope.unSelectCompany = function(id,idx,isCur){
    if (isCur){
      $scope.simuCurCompanyListed = [];
      $scope.item.nowJjgsId = "";
      $scope.item.dqgzdsmjjgs = "";
    }else{
      $scope.simuCompanyListed.splice(idx,1);
    }
  };

  simuManagerService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail;
    $scope.simuCurCompanyListed = [json.nowCompany];
    $scope.simuCompanyListed = json.beforeCompanyList;
    $scope.loading = false;
  });
  
  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先正确填写表单");
      return;
    }else{
      if($scope.simuCompanyListed.length){
        $scope.item.beforeJjgsIds = $scope.item.beforeJjgsIds || "";
        var beforeJjgsIdsList = $scope.item.beforeJjgsIds.split(",");
        angular.forEach($scope.simuCompanyListed,function(o){
          beforeJjgsIdsList.push(o.id);
        });
        $scope.item.beforeJjgsIds = beforeJjgsIdsList.join(",").trim(",");
      }
      simuManagerService.edit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $location.path("/simu/manager/list");
        }
      });
    }
  };
   $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.jlzpdz = response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  }); 
}]);

faApp.controller('SimuManagerViewCtrl',['$scope','$sce','simuManagerService','$location','$controller','$route','$routeParams',function($scope,$sce,simuManagerService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.nowCompany = {};
  $scope.beforeCompanyList = [];
  $scope.loading = true;
  $scope.id = $routeParams.id;
  
  simuManagerService.query({id:$scope.id}).then(function(json){
    $scope.item = json.detail;
    $scope.beforeCompanyList = json.beforeCompanyList;
    $scope.nowCompany = json.nowCompany;
      //前台html展示
    $scope.item.jjjljs=$sce.trustAsHtml($scope.item.jjjljs);
  });

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	}; 
  
  $scope.remove = function(id){
    simuManagerService.remove({id:id}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $location.path("/simu/manager/list");
      }
    });
  };
}]);







faApp.controller('SimuNdyjCtrl',['$scope','simuService','simuNdyjService','$location','$controller','$routeParams','$filter',function($scope,simuService,simuNdyjService,$location,$controller,$routeParams,$filter) {   
   
	$controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.formData = {id:$scope.id};
  $scope.item = {};
  $scope.jj = {};
  $scope.list = [];
  $scope.loading = true; 
  simuService.query({id:$scope.id}).then(function(json){
    $scope.jj = json.detail;
    json.detail.ndyjbJson = App.filterSimuJson(json.detail.ndyjbJson) || "{}";
    $scope.list = angular.fromJson(json.detail.ndyjbJson);
    if ($scope.list.length != undefined)$scope.list = {};
    $scope.list["1"] = $scope.list["1"] || {"ndyjsjz":"2014年"};
    $scope.list["2"] = $scope.list["2"] || {"ndyjsjz":"2013年"};
    $scope.list["3"] = $scope.list["3"] || {"ndyjsjz":"2012年"};
    $scope.list["4"] = $scope.list["4"] || {"ndyjsjz":"2011年"};
    $scope.list["5"] = $scope.list["5"] || {"ndyjsjz":"2010年"};
    $scope.list["6"] = $scope.list["6"] || {"ndyjsjz":"2009年"};
    $scope.list["7"] = $scope.list["7"] || {"ndyjsjz":"2008年"};
    $scope.formData.jjbm = $scope.jj.jjbm;
    $scope.edit(1);
    $scope.item.createBy = $scope.jj.createBy;
  }); 

  $scope.edit = function(v){
    $scope.itemIndex = v;
    $scope.item = $scope.list[v];
  };


  $scope.save = function(deleteFlag){ 
    $scope.jj.ndyjbJson = angular.toJson($scope.list);
    $scope.formData.ndyjbJson = angular.toJson($scope.list);
    simuNdyjService.edit($scope.formData).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.addAlert("操作成功");
        $scope.item = {};
        $scope.itemIndex = undefined;
      }
    });
  };
 
}]);

faApp.controller('SimuOrderListCtrl',['$scope','simuOrderService','$location','$controller','$route','orderManagerService','sessionService','authService',function($scope,simuOrderService,$location,$controller,$route,orderManagerService,sessionService,authService) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];
  $scope.loading = true;
	$scope.$watch('config',function(){
    simuOrderService.list($scope.config).then(function(json){
      $scope.list = json.list;
      $scope.pager = json.page;
      $scope.loading = false;
    
      angular.forEach($scope.list,function(o,i){
        $scope.list[i]['faInfo']['faShowName'] = $scope.list[i].faInfo.uName || $scope.list[i].faInfo.uRealName || $scope.list[i].faInfo.uLogin;
      });
    });
  },true)
 
	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1
	};
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	};   

  $scope.searchMap = {
		"jjmc" : '', 
  };

  if($scope.orderManagerUserList == undefined){
    var access = sessionService.getItem("user.access","");
    var tmp = "";
    if (access == "all"){
       tmp = "in";
    }else{
      angular.forEach(access.split(","),function(o){
        
        if(o.indexOf("queryOrderManagerUsersList.shtml") == 0){
          tmp = "in";
        }
      });
    }

    if(tmp != undefined && tmp.length){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList = json.list;
          $scope.orderManagerUserList.unshift({userId:"isnoManagerUser",username:"无跟进人订单"});
        }
      });
    }
  }

  $scope.isShowOrder = false;
  $scope.orderList = [];
  $scope.fit={};

  simuOrderService.queryOrderList($scope.fit).then(function(json){
    $scope.orderList=json.list || [];
  });

     //点击事件显示消息
$scope.changeShow=function(){
    $scope.isShowOrder = true;
 

}
//显示样式改变
$("#changecss").mouseover(function(){
$("#changecss").removeClass("markyanse");
  $("#changecss").addClass("changeCSS");
});
$("#changecss").mouseleave(function(){
$("#changecss").addClass("markyanse");
  $("#changecss").removeClass("changeCSS");
});




  $scope.search = function(){
    $scope.searchMap.isnoManagerUser = "";
    if($scope.searchMap.systemUserId != undefined && $scope.searchMap.systemUserId == "isnoManagerUser"){
      $scope.searchMap.isnoManagerUser = "yes";
    }
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
  $scope.process = function(id){
    simuOrderService.edit({id:id,'status':'02'}).then(function(json){
      if (json.statusCode){
         if(json.statusCode=='2007'){
          alert("订单状态不能逆转!!!!");
          return;
         }else{
           alert("出错了:" + json.statusCode);
         }
      }else{
        $route.reload();
      }
    });
  };

  $scope.chkAllOrderList = function(){
    if($("#chkAllOrderList").attr("checked") == "checked"){
      $("[name='chkOrderList']").attr("checked","checked");
    }else{
      $("[name='chkOrderList']").attr("checked",false);
    }
  };

  $scope.chooseOrderId = "";
  $scope.faids = "";
  $scope.omu = "";
  $scope.chooseOrderIdCount = 0;
  $scope.isShowOrderManagerLayer = false;
  $scope.t = "";
  
  $scope.orderDoOrder = function(t){
    chooseOrderList(t);
    if($scope.chooseOrderId != undefined && $scope.chooseOrderId != ""){
      $scope.chooseOrderIdCount = $scope.chooseOrderId.split(",").length - 1;
      $scope.isShowOrderManagerLayer = true;
    }else{
      alert("请选择订单！");
      return;
    }

    if(t != undefined && t != "" && t == "1"){
      orderManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.orderManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };

  chooseOrderList = function(t){
    $scope.chooseOrderId = "";
    $scope.omu = "";
    $scope.faids = "";
    $("[name='chkOrderList']").each(function(i){
      if($(this).attr("checked") == "checked"){
        if(t == 1 && $(this).attr("omu")){
          alert("请选择没有订单管理员的订单！");
          $scope.chooseOrderId = -1;
          return false;
        }else if(t == 0 && !$(this).attr("omu")){
          alert("请选择有订单管理员的订单！");
          $scope.chooseOrderId = -2;
          return false;
        }
        
        if($(this).attr("value") != undefined && $(this).attr("value") != ""){
          $scope.chooseOrderId += $(this).attr("value") + ",";
          $scope.faids += $(this).attr("faid") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
    //return $scope.chooseOrderId;
  };

  $scope.managerOrder = {};
  $scope.fenpeiOrHuishou = function(t){
    $scope.managerOrder.orderIds = $scope.chooseOrderId;
    $scope.managerOrder.ptype = "05";
    $scope.managerOrder.faids = $scope.faids;

    if(t == "1"){
      if($scope.managerOrder.systemUserId != undefined && $scope.managerOrder.systemUserId != "" && t != ""){
        // 分配操作
        $scope.managerOrder.isConfirm = "0";
        orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
          if (json.statusCode){
            if(json.statusCode == '4001'){

              var tmp = "理财师已被分配给了不同的渠道，请确认操作！\r";
              if(json.mess != undefined){
                angular.forEach(json.mess, function(o){
                  tmp += "理财师" + o.uid + "已被分配给：" + o.name + ";\r";
                });
              }

              if(confirm(tmp || "理财师已被分配给了不同的渠道，请确认操作！")){
                $scope.managerOrder.isConfirm = "1";
                orderManagerService.managerOrderUserAdd($scope.managerOrder).then(function(json){
                  if (json.statusCode){
                    alert("出错了:" + json.statusCode);
                  }else{
                    // 操作成功！分配成功！
                    $scope.alertNextPage("分配成功！");
                    $route.reload();
                  }
                });
              }
            }else{
              alert("出错了:" + json.statusCode);
            }
          }else{
            // 操作成功！分配成功！
            $scope.alertNextPage("分配成功！");
            $route.reload();
          }
        },function(res){
          alert('网络状态不稳定或超时！');
        });
      }else{
        alert("请选择订单管理员！");
      }
    }else if(t == '0'){
      var tmpid = "";
      angular.forEach($scope.omu.split(","),function(o,i){
        if(i == 0){
          tmpid = o;
        }else{
          if(o != undefined && o != "" && o != tmpid){
            tmpid = "99";
          }
        }
      });

      if(tmpid != undefined && tmpid != "99"){
        // 回收时，订单跟进人设为空
        $scope.managerOrder.systemUserId = "";
        // 回收
        orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      }else{
        if(confirm("选择了多笔跟进人不同的订单，确认要同时回收吗！")){
          // 回收时，订单跟进人设为空
          $scope.managerOrder.systemUserId = "";
          // 回收
          orderManagerService.managerOrderUserUpdate($scope.managerOrder).then(function(json){
            if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }
  };
  
}]); 

faApp.controller('SimuOrderViewCtrl',['$scope','simuOrderService','$location','$controller','$route','$routeParams',function($scope,simuOrderService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.loading = true;
  $scope.review = {'status':'02','id':$scope.id};

  simuOrderService.query({id:$scope.id}).then(function(json){
    if (json.list.length){
      $scope.item = json.list[0] || {};
      $scope.item['faInfo']['faShowName'] = $scope.item.faInfo.uName || $scope.item.faInfo.uRealName || $scope.item.faInfo.uLogin;
    }
    $scope.loading = false;
    
  });
  
  $scope.save = function(id){
    simuOrderService.edit($scope.review).then(function(json){
      if (json.statusCode){
        if(json.statusCode=='2006'){
          alert("还有附件未通过审核!!!!");
          return;
        }else if(json.statusCode=='2007'){
          alert("订单状态不能逆转!!!!");
          return;
        }else{
           alert("出错了:" + json.statusCode);
        }
      }else{
        alert("操作成功");
        $location.path("/simu/order/list");
      }
    });

    // $location.path("/simu/order/list");
  };
 
}]);

faApp.controller('SimuSpnrCtrl',['$scope','simuService','roadVideoService','$location','$controller','$routeParams','$filter','$route',function($scope,simuService,roadVideoService,$location,$controller,$routeParams,$filter,$route) {
   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.jjbm = $routeParams.jjbm;
  $scope.spnr = {};
  $scope.player = '';
  roadVideoService.list({isProduct:'0',pageSize:1000,pageNo:1}).then(function(json){
    $scope.list = json.list;
  });
  simuService.query({jjbm:$scope.jjbm}).then(function(json){
    $scope.jj = json.detail;
    $scope.videoInfoPost = {
      productType:'01',
      productId:$scope.id
    }
    roadVideoService.videoIdbyPro($scope.videoInfoPost).then(function(json){
      $scope.oldId = json.dto ? json.dto.id : '';
      $scope.title = json.dto ? json.dto.title : '';

    })
  });



   $scope.save=function(){

      if($scope.newVideoId==null||$scope.newVideoId==''){
        alert("视频名称不能为空");
        return ;
      }
      $scope.spnr.productType="01";
      $scope.spnr.productId=$scope.id;
      $scope.spnr.oldId = $scope.oldId;
      $scope.spnr.id = $scope.newVideoId;
       roadVideoService.edit($scope.spnr).then(function(json){
         if(!json.statusCode){
           alert("修改成功");
           $route.reload()
         }else{
           alert(json.statusCode);
         }
       });
   }

   $scope.playVideo = function(v){
    if(!v){
      alert('请选择视频');
      return;
    }else{
      for( arr in $scope.list){
        if($scope.list[arr].id == v){
          $scope.videoId = $scope.list[arr].videoId;
        };
      }
    };
    if($scope.videoId){
      $scope.showPlayBox = true;
      $scope.player = new YKU.Player('youkuplayer',{
        styleid: '0',
        client_id: YK_CLIENT_ID,
        vid: $scope.videoId,
        newPlayer: true
      })
    }

  }

   $scope.stopPlay = function(){
     $scope.videoId = '';
     $scope.showPlayBox = false;
   }




}]);

faApp.controller('StatisticalOrderCtrl', ['$scope','StatisticalService','exportService','$location','$controller','$routeParams','$filter',
function($scope,StatisticalService,exportService,$location,$controller,$routeParams,$filter) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.list = [];
  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      StatisticalService.orderList($scope.config).then(function(json){
        $scope.list = json.list;

        $scope.pager = json.pager;
        $scope.loading = false;
      });
    } 
  },true);

  $scope.orderListCsv = function(){
    exportService.exportCSV($scope.config,"STATISTICAL_ORDER_LIST_CSV");
  }
}
]);

faApp.controller('StatisticalUserCtrl', ['$scope','StatisticalService','exportService','$location','$controller','$routeParams','$filter',
function($scope,StatisticalService,exportService,$location,$controller,$routeParams,$filter) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.list = [];

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      StatisticalService.userList($scope.config).then(function(json){
        $scope.list = json.list;
        $scope.pager = json.pager;
        $scope.loading = false;
      });
    } 
  },true);

  $scope.userListCsv = function(){
    exportService.exportCSV($scope.config,"STATISTICAL_USER_LIST_CSV");
  }
}
]);

faApp.controller('statisticsRegisterCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsFaRegisterByMonth().then(function (json) {
        if (!json.statusCode) {
            var xdata = [];
            var ydata = [];
            var data = [];
            angular.forEach(json.list, function (o, i) {
                xdata.push(o.dmonth);
                ydata.push(o.num);
                data.push(o.num);
            });

            $scope.option = {
                title: {
                    text: '每月注册量'
                },
                tooltip: {},
                legend: {
                    data: ['人数']
                },
                xAxis: {
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: xdata
                },
                yAxis: {},
                series: [{
                    name: '人数',
                    type: 'bar',
                    data: ydata
                }]
            };
        }
    });
}]);

faApp.controller('statisticsRegisterRoleCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsFaUserRoleCount().then(function (json) {
        if (!json.statusCode && json.list) {
            var data = [];
            var d = json.list[0];
            data.push({value: d.weitijiao, name: '未提交审核'});
            data.push({value: d.shenhezhong, name: '审核中'});
            data.push({value: d.shibai, name: '审核失败'});
            data.push({value: d.tongguo, name: '审核通过'});


            $scope.option = {
                title: {
                    text: '审核状态统计',
                    // subtext: '',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: ['未提交审核', '审核中', '审核失败', '审核通过']
                },
                series: [
                    {
                        name: '状态',
                        type: 'pie',
                        radius: '75%',
                        center: ['40%', '60%'],
                        data: data,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsOrderCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsOrderByMonth().then(function (json) {
        if (!json.statusCode) {
            var xdata = [];
            var ydata1 = [];
            var ydata2 = [];

            angular.forEach(json.list, function (o, i) {
                xdata.push(o.saleMonth);
                ydata1.push(o.oAmount);
                ydata2.push(o.orderCount);
            });

            $scope.option = {
                title: {
                    text: '订单数据',
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function (p) {
                        return '成交量:' + p[0].name + ' <br> 成交金额:' + $filter("moneyRender")(p[0].value);
                    }
                },
                legend: {
                    selectedMode: false,
                    data: ['成交量', '成交金额']
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: true,
                        data: xdata
                    },
                    {
                        type: 'category',
                        boundaryGap: true,
                        data: ydata2
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        scale: true,
                        name: '成交量'
                    },
                    {
                        type: 'value',
                        scale: true,
                        name: '金额',
                        axisLabel: {
                            formatter: function (v, i) {
                                return $filter("moneyRender")(v);
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '成交金额',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: ydata1
                    },
                    {
                        name: '成交量',
                        type: 'line',
                        data: ydata2
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsOrderUserPerCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsOrderUserPer().then(function (json) {
        if (!json.statusCode && json.dto) {
            var data = [];
            var d = json.dto;
            data.push({value: (d.allUserCount - d.noHasOrderUserCount), name: '认证下单人数'});
            data.push({value: d.noHasOrderUserCount, name: '认证未下单人数'});

            $scope.option = {
                title: {
                    text: '审核状态统计',
                    // subtext: '',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: ['认证下单人数', '认证未下单人数']
                },
                series: [
                    {
                        name: '状态',
                        type: 'pie',
                        radius: '75%',
                        center: ['40%', '60%'],
                        data: data,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsOrderFauserRolePrpportionCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsOrderFauserRolePrpportion().then(function (json) {
        if (!json.statusCode && json.list) {
            var data = [];
            var legendData = [];
            var d = json.list;

            angular.forEach(json.list, function (o, i) {
                var s = $filter("faRoleStatusRender")('01', o.uRole);
                data.push({value: o.roleCount, name: s});
                legendData.push(s);
            });

            $scope.option = {
                title: {
                    text: '订单-理财师角色比例',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: legendData
                },
                series: [
                    {
                        name: '状态',
                        type: 'pie',
                        radius: '75%',
                        center: ['50%', '50%'],
                        data: data,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsOrderFauserPrpportionCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsOrderFauserPrpportion().then(function (json) {
        if (!json.statusCode && json.list) {
            var data = [];
            var legendData = [];
            var d = json.list;

            angular.forEach(json.list, function (o, i) {
                var s = $filter("faRoleStatusRender")('01', o.uRole);
                data.push({value: o.roleCount, name: s});
                legendData.push(s);
            });

            $scope.option = {
                title: {
                    text: '认证理财师角色比例',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: legendData
                },
                series: [
                    {
                        name: '状态',
                        type: 'pie',
                        radius: '75%',
                        center: ['50%', '50%'],
                        data: data,
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsOrderRankingCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsOrderUserTotal({pageSize: 10, pageNo: 1}).then(function (json) {
        if (!json.statusCode && json.list) {
            var datay = [];
            var datax = [];
            var dataid = [];
            var tt = '';

            angular.forEach(json.list.reverse(), function (o, i) {
                tt = o.faId + ',,,' + (o.uRealName || '');

                datay.push(tt);
                datax.push(o.oAmount);
            });

            $scope.option = {
                title: {
                    text: '用户订单排行',
                    subtext: 'SFA排名前十的理财师'
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function (p) {
                        return '成交金额<br>' + $filter("moneyRender")(p[0].value);
                    }
                },

                legend: {
                    data: ['订单总额']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: datay,
                    axisLabel: {
                        formatter: function (v, i) {
                            return v.split(',,,')[1];
                        }
                    }
                },
                series: [
                    {
                        name: '订单总额',
                        type: 'bar',
                        data: datax
                    }
                ]
            };
        }
    });
}]);

faApp.controller('statisticsCompanyTotalCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    statisticsService.statisticsCompanyTotal({pageSize: 10, pageNo: 1}).then(function (json) {
        if (!json.statusCode && json.list) {
            var datay = [];
            var datax = [];

            angular.forEach(json.list.reverse(), function (o, i) {
                datay.push(o.cName);
                datax.push(o.productCount);
            });

            $scope.option = {
                title: {
                    text: '供应方排行'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['产品数量']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: datay,
                    axisLabel: {
                        formatter: function (v, i) {
                            return v.substr(0, 15);
                        }
                    }
                },
                series: [
                    {
                        name: '产品数量',
                        type: 'bar',
                        data: datax
                    }
                ]
            };
        }
    });
}]);

faApp.controller('productKeyWordTotalCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', '$filter', 'statisticsService', function ($scope, $location, $controller, $route, $routeParams, $filter, statisticsService) {
    $controller('BaseCtrl', {$scope: $scope});

    var feedbackStatus = new Object();
    $scope.feedbackStatus = feedbackStatus;


    var value = {};

    var searchKeyWord = new Object();
    $scope.searchKeyWord = searchKeyWord;
    $scope.config = {
        "pageSize" : 20,
        "pageNo" : 1,
        "feedbackStatus":value,
        "jjbm" : $routeParams.jjbm || ""
    };
    var initData = function (data) {
        console.log(data);
        statisticsService.statisticsProductKeyWord(data).then(function (json) {
            searchKeyWord.data = json.list;
            searchKeyWord.pager = json.pager;
            // searchKeyWord.pager.totalCount = json.count;
        });
    }
    initData($scope.config);

    $scope.pageChanged = function(){
        $scope.config = {
            "pageSize" : 20,
            "pageNo" : 1,
            "feedbackStatus":value,
            "jjbm" : $routeParams.jjbm || ""
        };
        $scope.config.pageNo = searchKeyWord.pager.pageNo;
        initData($scope.config);
    };

    $scope.query = function (data) {
        value = data;
        $scope.config = {
            "pageSize" : 20,
            "pageNo" : 1,
            "feedbackStatus":value,
            "jjbm" : $routeParams.jjbm || ""
        };
        initData($scope.config);
    }

    //未反馈关键词发送消息
    $scope.sendMsg = function (data) {
        if(confirm('无法找到并创建此关键字产品时使用此功能，确认回复？')) {
            var xcxNews = {};
            xcxNews.keyWord = data.keyword;
            xcxNews.content = "此产品没有哇！！！！！！！！！！";
            xcxNews.proUrl = "";
            xcxNews.content = "尊敬的用户，您搜索的产品关键字'"+data.keyword+"'查无此产品!";
            statisticsService.statisticsSendMsg(xcxNews).then(function (json) {
                console.log(json)
                alert('回复成功！')
                $route.reload();
            })
        }
    }

    $scope.showXcxUser = function (item, list) {
        var isshow = item.checked;
        for(var i=0; i<list.length; i++) {
            var d = list[i];
            d.checked = false;
        }
        item.checked = !isshow;

        statisticsService.statisticsProductKeyWordUser({keyword: item.keyword, searchType: item.searchType, feedbackStatus:item.feedbackStatus}).then(function (json) {
            $scope.searchUserList = json.list
        })
    }
}]);
angular.module('faApp')
  .service('statisticsService', [ 'ajaxService',function (ajaxService) {

    this.statisticsFaRegisterByMonth = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_FA_REGISTER_BY_MONTH"), cfg || {});
    };
    this.statisticsFaUserRoleCount = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_FAUSER_ROLE_COUNT"), cfg || {});
    };
    this.statisticsRegisterAllCount = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_REGISTER_ALL_COUNT"), cfg || {});
    };
    this.statisticsOrderByMonth = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_ORDER_BY_MONTH"), cfg || {});
    };
    this.statisticsOrderUserPer = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_ORDER_USER_PER"), cfg || {});
    };
    this.statisticsOrderFauserRolePrpportion = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_ORDER_FAUSER_ROLE_PROPORTION"), cfg || {});
    };
    this.statisticsOrderFauserPrpportion = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_ORDER_FAUSER_PROPORTION"), cfg || {});
    };

    this.statisticsOrderUserTotal = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_ORDER_USER_TOTAL"), cfg || {});
    };

    this.statisticsCompanyTotal = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("STATISTICS_COMPANY_TOTAL"), cfg || {});
    };

    this.statisticsProductKeyWord = function (data) {
        return ajaxService.post(ajaxService.getApiUri("STATISTICS_PRODUCT_KEYWORD"),data || {});
    }
    this.statisticsProductKeyWordUser = function (data) {
        return ajaxService.post(ajaxService.getApiUri("STATISTICS_PRODUCT_KEYWORD_USER"),data || {});
    }

    this.statisticsSendMsg = function (data) {
        return ajaxService.post(ajaxService.getApiUri("STATISTICS_SEND_MSG"),data || {});
    }

}]);
faApp.controller('SupplierListCtrl',['$scope','supplierService','$location','$controller','$route','$routeParams',function($scope,supplierService,$location,$controller,$route,$routeParams) {
  
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.list = [];
  $scope.loading = true;
  //// console.log('aa');

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      supplierService.supplierList($scope.config).then(function(json){
        $scope.list = json.list;
		    $scope.pager = json.pager;
		    $scope.loading = false;
      });
    }
  },true);
}]);

faApp.controller('SupplierFlowListCtrl',['$scope','supplierService','$location','$controller','$route','$routeParams',function($scope,supplierService,$location,$controller,$route,$routeParams) {
  
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.list = [];
  $scope.loading = true;
  $scope.accessId = $routeParams.accessId;

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      
      $scope.config['accessId'] = $scope.accessId;

      supplierService.supplierFlowList($scope.config).then(function(json){
        $scope.list = json.list;
        $scope.pager = json.pager;
        $scope.loading = false;
      });
    }
  },true);
}]);

faApp.controller('SupplierAddCtrl',['$scope','supplierService','$location','$controller','$timeout',function($scope,supplierService,$location,$controller,$timeout) {   
  $controller('BaseCtrl', {$scope: $scope});

  $scope.item = {};
  $scope.loading = true;

  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else{
      if(($scope.item.accessMobile + "").length != 11){
        alert("手机号长度必须为11位！");
        return;
      }
      if(($scope.item.accessMobile + "").substr(0,1) != "1"){
        alert("手机号第一位必须是1!");
        return;
      }
      supplierService.supplierAdd($scope.item).then(function(json){
        if (json.statusCode){
          if(json.statusCode == '2003'){
            alert("供应方公司名重复！");
          }else{
            alert("出错了:" + json.statusCode);
          }
        }else{
          $scope.alertNextPage("操作成功");
          $location.path("/supplier/list");
        }
      });
    }
  };
}]);

faApp.controller('SupplierEditCtrl',['$scope','supplierService','$location','$controller','$routeParams','$filter',function($scope,supplierService,$location,$controller,$routeParams,$filter) {   
  $controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.loading = true; 
  $scope.id = $routeParams.id;
  
  supplierService.supplierDetail({id:$scope.id}).then(function(json){
    $scope.loading = false;
    $scope.item = json['dto'];
    $scope.item.accessMobile = parseInt(json['dto'].accessMobile);
  });

  $scope.save = function(){
    if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else{

      supplierService.supplierEdit($scope.item).then(function(json){
        if (json.statusCode){
          if(json.statusCode == '2003'){
            alert("供应方公司名重复！");
          }else{
            alert("出错了:" + json.statusCode);
          }
        }else{
          $scope.alertNextPage("操作成功");
          $location.path("/supplier/list");
        }
      });
    }
  };
}]);
faApp.controller('SwitchListCtrl',['$scope','switchService','$location','$controller','$route',
  function($scope,switchService,$location,$controller,$route) {   

    $controller('BaseCtrl', {$scope: $scope}); 

    $scope.switchs = [];
    $scope.loading = true;

    $scope.$watch('config',function(){
      switchService.switchList($scope.config).then(function(json){
        $scope.switchs = json.list;
        $scope.pager = json.pager;
        $scope.loading = false;
      });
    },true);

    $scope.changeSwitch = function(id,status){

      switchService.switchUpdate({id:id,sValue:status}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $route.reload();
        }
      });
    }
  }]);
faApp.controller('System403Ctrl',['$scope','userService','$location','$controller',function($scope,userService,$location,$controller) {   
	$controller('BaseCtrl', {$scope: $scope}); 

}]); 


faApp.controller('ToolsUploadCtrl',['$scope','userService','$location','$controller',function($scope,userService,$location,$controller) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.picAddre = App.staticHost + response.attribute.fileUrl;
        $scope.$apply();
      } else { 
        alert('上传失败'); 
      }
    }    
  });
}]); 

/*** 更新订单**/
faApp.controller('UpdateOrderCtrl',['$scope','updateOrderService','$location','$controller','$routeParams','$filter','$route',function($scope,updateOrderService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.param={};
  $scope.param.orderId=$routeParams.orderId;
  $scope.orderFlowList={};//订单追踪时间
  $scope.orderDateInfo={};//订单时间
  $scope.item={};//订单基本信息
  //待提交参数
  $scope.orderFlow=[];//跟踪时间
  $scope.orderFlowId=[];//跟踪时间
  $scope.orderFlowEnd=[];//跟踪时间后缀
  $scope.dateparam={};//时间

  updateOrderService.queryOrderDetail($scope.param).then(function(json) {
     if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
         $scope.item=json.orderVo;
         $scope.orderDateInfo=json.orderInfo;
         $scope.orderFlowList=json.orderFlowList;
         //时间格式处理
         angular.forEach($scope.orderFlowList,function(o,i){
          $scope.orderFlow[i]=$filter("date")(o.flowDate,"yyyy-MM-dd");
          $scope.orderFlowEnd[i]=$filter("limitTo")(o.flowDateStr,-8);
         });
         //订单时间   后缀
         $scope.dateparam.orderCreateDate=$filter("limitTo")($scope.orderDateInfo.orderCreateDate,10);
         $scope.dateparam.orderCreateDateEnd=$filter("limitTo")($scope.orderDateInfo.orderCreateDate,-8);
        //用户认证时间   后缀
         $scope.dateparam.userAuthDate=$filter("limitTo")($scope.orderDateInfo.userAuthDate,10);
         $scope.dateparam.userAuthDateEnd=$filter("limitTo")($scope.orderDateInfo.userAuthDate,-8);
        //用户注册时间   后缀
         $scope.dateparam.userCreateDate=$filter("limitTo")($scope.orderDateInfo.userCreateDate,10);
         $scope.dateparam.userCreateDateEnd=$filter("limitTo")($scope.orderDateInfo.userCreateDate,-8);
      }
  });

  $scope.save = function(){
    if (!$scope.form.$valid) {
      alert("请先完整填写表单");
      return;
    }
    
    if($scope.dateparam.userAuthDate){
      if($scope.dateparam.userAuthDateEnd){
         $scope.dateparam.userAuthDate+=' ' +$scope.dateparam.userAuthDateEnd;
      }else{
        alert("请完整填写认证时间");
        return;
      }
    }else if($scope.dateparam.userAuthDateEnd){
      if($scope.dateparam.userAuthDate){
         $scope.dateparam.userAuthDate+=' ' +$scope.dateparam.userAuthDateEnd;
      }else{
        alert("请完整填写认证时间");
        return;
      }
    }
    //注册时间是否小于订单预约时间
    var uCreateDate=$scope.dateparam.userCreateDate+' ' +$scope.dateparam.userCreateDateEnd;
    var oCreateDate=$scope.dateparam.orderCreateDate+' ' +$scope.dateparam.orderCreateDateEnd;
    console.log(uCreateDate+"="+oCreateDate);
    if(uCreateDate>oCreateDate){
      alert("注册时间必须小于订单预约时间");
      return ;
    }
    $scope.orderFlowParam=[];
    //拼接跟踪时间
    for (k in $scope.orderFlow){
      $scope.orderFlowParam[k] =$scope.orderFlow[k] +' ' + $scope.orderFlowEnd[k];
      if(k>0){
        if($scope.orderFlowParam[k-1]>$scope.orderFlowParam[k]){
          alert("订单追踪时间存在错误!");
          return ;
        }
      }
    }

    delete $scope.dateparam.userAuthDateEnd;
    //拼时间
    $scope.dateparam.userCreateDate+=' ' +$scope.dateparam.userCreateDateEnd;
    delete $scope.dateparam.userCreateDateEnd;
    $scope.dateparam.orderCreateDate+=' ' +$scope.dateparam.orderCreateDateEnd;
    delete $scope.dateparam.orderCreateDateEnd;

    var p={
      'orderId':$scope.param.orderId,
      'orderFlowId':$scope.orderFlowId.join(","),
      'orderFlow':$scope.orderFlowParam.join(","),
      'dateparam':angular.toJson($scope.dateparam)
    };  

    updateOrderService.updateOrderDetail(p).then(function(json) {
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功");
          $route.reload();
        }
    });
  }
  //2017 节假日
  var holiday="2017-10-01,2017-10-02,2017-10-03,2017-10-04,2017-10-05,2017-10-06,2017-10-07,2017-10-08";

  /*** 自动生成 时分秒   ***/
  $scope.upDate=function(v){
    if(v!='220'){
      return ;
    }

    var dksj;// 已签约打款  基础时间
    for (k in $scope.orderFlowList){
      var o=$scope.orderFlowList[k];
      if(o.oStatus=='220'){
        dksj=$scope.orderFlow[k];
        var a=$scope.orderFlowEnd[k];
        //是否正常时间
        if(a==undefined||!/^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$/.test(a)
         ||dksj==undefined||!/^20\d{2}-\d{2}-\d{2}$/.test(dksj)
         ){
          return ;
        }
        //是否大于当前时间
         var date=new Date(dksj+" "+a);
        if(date>=new Date()){
          alert("签约时间不能大于当前时间!");
          return;
        }
        break;
      }
    }
    for (k in $scope.orderFlowList) {
      var o=$scope.orderFlowList[k];
      var status = parseInt(o.oStatus);
      if(status==110){//提交预约
        var endDay=daysJian(dksj,-daysRandom(3,5));
        $scope.orderFlow[k]=$filter("date")(endDay,"yyyy-MM-dd");
        //预约时间
        $scope.dateparam.orderCreateDate=$scope.orderFlow[k];

        console.log("预约时间:"+endDay);
      }else if(status<=130){//预约成功 中间状态 最多8小时
        var endDay=$scope.orderFlow[k-1];
        var endDayHour=$scope.orderFlowEnd[k-1];
        var s = addRandomHours(endDay+" "+endDayHour,1,4);
        $scope.orderFlow[k]=$filter("date")(s,"yyyy-MM-dd");
        $scope.orderFlowEnd[k]=$filter("date")(s,"HH:mm:ss");
      }else if(status==220){//基准时间  已签约打款 不动

      }else if(status>220&&status<=240){//确认打款  1个工作日内
        var endDay=$scope.orderFlow[k-1];
        var endDayHour=$scope.orderFlowEnd[k-1];
        var s = addRandomHours(endDay+" "+endDayHour,2,12);
        $scope.orderFlow[k]=$filter("date")(s,"yyyy-MM-dd");
        $scope.orderFlowEnd[k]=$filter("date")(s,"HH:mm:ss");
      }
      else if(status>240&&status<320){//15个工作日
        var endDay=$scope.orderFlow[k-1];
        var endDayHour=$scope.orderFlowEnd[k-1];
        var s = addRandomHours(endDay+" "+endDayHour,5,24);
        $scope.orderFlow[k]=$filter("date")(s,"yyyy-MM-dd");
        $scope.orderFlowEnd[k]=$filter("date")(s,"HH:mm:ss");
      }else if(o.oStatus==320){
        var endDay=$scope.orderFlow[k-1];
        var endDayHour=$scope.orderFlowEnd[k-1];
        var s = addRandomHours(endDay+" "+endDayHour,1,5);
        $scope.orderFlow[k]=$filter("date")(s,"yyyy-MM-dd");
        $scope.orderFlowEnd[k]=$filter("date")(s,"HH:mm:ss");
      }else{
        var endDay=$scope.orderFlow[k-1];
        var endDayHour=$scope.orderFlowEnd[k-1];
        var s = addRandomHours(endDay+" "+endDayHour,2,10);
        $scope.orderFlow[k]=$filter("date")(s,"yyyy-MM-dd");
        $scope.orderFlowEnd[k]=$filter("date")(s,"HH:mm:ss");
      }

    };
  }

  /** 时间  设置天数 -1 天 **/
  function daysJian(d,day){
   //判断工作日内加
   var date=new Date(d);
   //循环加1   工作日
   for (var i = 1; i <= Math.abs(day); i++) {
     date.setDate(date.getDate()+(day>0?1:-1));
     var dstr = $filter("date")(date,"yyyy-MM-dd");
     if(date.getDay()==0||date.getDay()==6||holiday.indexOf(dstr)>=0){
        i--;
     }
   };
   console.log("add day end="+$filter("date")(date,"yyyy-MM-dd"));
   return date;
  }  
    /** 时间  设置小时 随机分钟 **/
  function addRandomHours(d,min,max){
   //判断工作日内加
   var date=new Date(d);
   var addHours=date.getHours()+daysRandom(min,max);
   console.log("add addRandomHours ="+$filter("date")(date,"yyyy-MM-dd"));
   if(addHours>20){//小时超过晚上8点 天数+1
      date = daysJian(date,1);
      date.setHours(daysRandom(9,12));
      console.log("add addRandomHours>20 ="+$filter("date")(date,"yyyy-MM-dd"));
   }else{
    date.setHours(addHours);
    var dstr=$filter("date")(date,"yyyy-MM-dd");
     //判断当前是否工作日
    if(date.getDay()==0||date.getDay()==6||holiday.indexOf(dstr)>=0){
      date=daysJian(date,1);
      date.setHours(daysRandom(9,20));
    }
   }
   date.setMinutes(daysRandom(1,59));
   date.setSeconds(daysRandom(1,59));
 
   return date;
  }  
      /** 时间  随机工作时分秒    **/
  function randomWorkHousr(d){
   var date=new Date(d);
   date.setHours(daysRandom(9,20));  
   date.setMinutes(daysRandom(59,59));  
   date.setSeconds(daysRandom(59,59));  
   return date;
  } 
   /** 时间  随机中间数 **/
  function daysRandom(min,max){
    var day=Math.random()*(max-min)+min;
    return day;
  }  

}]);
/*** 更新产品**/
faApp.controller('UpdateProductDateCtrl',['$scope','updateOrderService','productService','$location','$controller','$routeParams','$filter','$route',function($scope,updateOrderService,productService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  
    $scope.param={};
    $scope.param.pId=$routeParams.pId;
    $scope.dateparam={};
     $scope.dateparam.pId= $scope.param.pId;
  //如果有值，则说明是点了复制按钮，则根据ID加载产品
    updateOrderService.queryOrderDetail($scope.param).then(function(json){
      $scope.project = json.projectVo;
      //开始销售时间   
      if(json.projectVo.pSaleTimeStart)
      $scope.dateparam.saleTimeStart=$filter("date")(json.projectVo.pSaleTimeStart,"yyyy-MM-dd");
      //结束销售时间   
      if(json.projectVo.pSaleTimeEnd)
        $scope.dateparam.saleTimeEnd=$filter("date")(json.projectVo.pSaleTimeEnd,"yyyy-MM-dd");

      $scope.minOrderCreateDate=json.minOrderCreateDate;
      $scope.maxOrderCreateDate=json.maxOrderCreateDate;

    });

  $scope.save = function(){
    if (!$scope.form.$valid) {
      alert("请先完整填写表单");
      return;
    }
    if($scope.dateparam.saleTimeEnd){
       //开始销售时间必须小于结束销售时间
      if($scope.dateparam.saleTimeStart>$scope.dateparam.saleTimeEnd){
        alert("注册时间必须小于订单预约时间");
        return ;
      }
    }
    var p={
      'pId':$scope.pid,
      'dateparam':angular.toJson($scope.dateparam)
    };  
    updateOrderService.updateOrderDetail(p).then(function(json) {
       if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("更新成功");
          $route.reload();
        }
    });
  }

}]);

/*** 新增可修改订单**/
faApp.controller('UpdateOrderAddCtrl',['$scope','updateOrderService','$location','$controller','$routeParams','$filter','$route',function($scope,updateOrderService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.save = function(){
   if ($scope.form.$invalid){
      alert("请先完整填写表单");
      return;
    }else{
      updateOrderService.saveOrderIdList({"idList":$scope.idList}).then(function(json){
      if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("新增成功");
          $route.reload();
        }
    });

    }
  }  
}]);
/*** 更新订单搜索 **/
faApp.controller('UpdateOrderListCtrl',['$scope','updateOrderService','$location','$controller','$routeParams','$filter',function($scope,updateOrderService,$location,$controller,$routeParams,$filter) {   
  $controller('BaseListCtrl', {$scope: $scope}); 


  $scope.list = [];
  $scope.loading = true;
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
       if($scope.config.orderIds!=undefined){
        console.log("query idList");
         updateOrderService.getOrderIdList($scope.config).then(function(json){
          if (json.statusCode){
              alert("出错了:" + json.statusCode);
          }else{
           $scope.orderList=json.orderList;

          }
        });
      }
     
    }
  },true)
   
}]);  
faApp.controller('UserListCtrl',['$scope','userService','$location','$controller',function($scope,userService,$location,$controller) {   
  $controller('BaseCtrl', {$scope: $scope});
  $scope.list = [];
  function getData(id){
    userService.userList({
      layerPath:id
    }).then(function(json){
      $scope.list = json.list || [];
    });
  }
  getData();
  userService.userListTree().then(function(json){
    console.log(json);
    //$scope.list = json.list || [];
    $(document).ready(function(){
      $.fn.zTree.init($("#treeDemo"), setting, json.list);
    });
  });
  var setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    callback:{ //回调函数
      /**
       * event:鼠标事件
       * treeId：树的容器id
       * treeNode：当前点击的节点
       */
      beforeClick:function(treeId,treeNode,clickFlag){
        console.log(treeNode);
        getData(treeNode.id);

      }
    }
  };

  //$scope.cktest = function(){

  //}





}]);

faApp.controller('UserAddCtrl',['$scope','userService','$location','$controller','authService',function($scope,userService,$location,$controller,authService) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {status:"0",userType:"02",sex:"1"};
  $scope.roleList = [];
  $scope.selectRoles = [];
  $scope.allRoles = {};

  authService.roleList().then(function(json){
    $scope.roleList = json.allGroup;  
  });
  var setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    callback:{ //回调函数
      /**
       * event:鼠标事件
       * treeId：树的容器id
       * treeNode：当前点击的节点
       */
      beforeClick:function(treeId,treeNode,clickFlag){

        console.log(treeNode);
        console.log($scope.selectedName);

        if($scope.selectedName == '1'){
          $scope.item.parentUserId = treeNode.id;
          $scope.item.parentUserName = treeNode.name;
        }else if($scope.selectedName == '2'){
          $scope.item.deptHeadName = treeNode.name;
          $scope.item.deptHead = treeNode.id;
        }else if($scope.selectedName == '3'){
          $scope.item.publicDeptHeadName = treeNode.name;
          $scope.item.publicDeptHead = treeNode.id;
        }

        $scope.$apply();
      }
    }
  };
  //获取部门列表
  $scope.getDepartment = function(){
    userService.userListTree().then(function(json){
      console.log(json);
      //$scope.list = json.list || [];
      $(document).ready(function(){
        $.fn.zTree.init($("#treeDemo"), setting, json.list);
      });
    });
  };
  $scope.getDepartment();

  $scope.save = function(){
    if ($scope.form.$valid){
      
      if(($scope.item.telePhone + "").length != 11){
        alert("手机号长度必须为11位！");
        return;
      }
      if(($scope.item.telePhone + "").substr(0,1) != "1"){
        alert("手机号第一位必须是1!");
        return;
      }

      var flag = false;
      for (var i in $scope.allRoles){
        if ($scope.allRoles[i]){
          flag = true;
          $scope.selectRoles.push(i);
        }
      }
      if (!flag){
        alert("请先选择权限");
        return;
      }
      $scope.item.groupId = $scope.selectRoles.join(",");
      delete $scope.item.parentUserId_name;

      userService.userAdd($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
          return;
        }else{
          $scope.alertNextPage("新增管理员成功！");
          $location.path("/user/list");
        }  
      });
    }else{
      alert("请先完整填写表单");
    }
  };
}]);

faApp.controller('UserEditCtrl',['$scope','userService','$location','$controller','$routeParams','authService',function($scope,userService,$location,$controller,$routeParams,authService) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.item = {};
  $scope.roleList = [];
  $scope.selectRoles = [];
  $scope.allRoles = {};
  $scope.id = $routeParams.id;

  authService.roleList().then(function(json){
    $scope.roleList = json.allGroup;  
  });
  var setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    callback:{ //回调函数
      /**
       * event:鼠标事件
       * treeId：树的容器id
       * treeNode：当前点击的节点
       * isParent 是否为父节点
       */
      beforeClick:function(treeId,treeNode,clickFlag){

        console.log(treeNode);
        //isParent 是否为父节点
        console.info(treeNode.isParent);

        if($scope.selectedName == '1'){
          $scope.item.parentUserId = treeNode.id;
          $scope.item.parentUserName = treeNode.name;
        }else if($scope.selectedName == '2'){
          $scope.item.deptHeadName = treeNode.name;
          $scope.item.deptHead = treeNode.id;
        }else if($scope.selectedName == '3'){
          $scope.item.publicDeptHeadName = treeNode.name;
          $scope.item.publicDeptHead = treeNode.id;
        }

        $scope.$apply();
      }
    }
  };
  //获取部门列表

  userService.userListTree().then(function(json){
    console.log(json);
    //$scope.list = json.list || [];
    $(document).ready(function(){
      $.fn.zTree.init($("#treeDemo"), setting, json.list);
    });
  });

  userService.userQuery($scope.id).then(function(json){
    $scope.item = json.userInfo;
    $scope.item.telePhone = parseInt(json.userInfo.telePhone);
    angular.forEach(json.selectGroups,function(o){
      $scope.allRoles[o.groupId] = true;  
    }); 
  });

  $scope.save = function(){
    if ($scope.form.$valid){
      if(($scope.item.telePhone + "").length != 11){
        alert("手机号长度必须为11位！");
        return;
      }
      if(($scope.item.telePhone + "").substr(0,1) != "1"){
        alert("手机号第一位必须是1!");
        return;
      }

      var flag = false;
      for (var i in $scope.allRoles){
        if ($scope.allRoles[i]){
          flag = true;
          $scope.selectRoles.push(i);
        }
      }
      if (!flag){
        alert("请先选择权限");
        return;
      }
      $scope.item.groupId = $scope.selectRoles.join(",");
      console.log($scope.item);

      userService.userEdit($scope.item).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
          return;
        }else{
          $scope.alertNextPage("新增管理员成功！");
          $location.path("/user/list");
        }  
      });
    }else{
      alert("请先完整填写表单");
    }
  };
  
   

}]);

faApp.controller('VarietyProductListCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', function($scope, $location, $controller, $route, $routeParams) {
    $scope.tabUrl = {};
    $scope.type = $routeParams.t;
    $scope.tabUrlMap = {
        samePro: "#/varietyProduct/samePro?type=" + $scope.type,
        // likePro: "#/varietyProduct/likePro?id=" + $scope.id,
        newPro: "#/varietyProduct/newPro?type=" + $scope.type,
    };
    $scope.changeTab = function(tab) {
        $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    };
    $scope.changeTab('samePro');
}]);
faApp.controller('SameProductListCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', "varietyService", function($scope, $location, $controller, $route, $routeParams, varietyService) {
    $controller('BaseListCtrl', {
        $scope: $scope
    });
    $scope.config.pType = $routeParams.type;
    $scope.config.pageSize = 10;
    $scope.config.productSource = "1caifu"; //设置壹财富来源
    $scope.$watch('config', function() {
        varietyService.yesBindingProList($scope.config).then(function(json) {
            $scope.list = json.bindProjectList;
            $scope.pager = json.page;


        })
    }, true);
    //标记为不同产品
    $scope.markDiff = function(o) {
        if( confirm('确定为不同产品') ) {            
            var idGroup = {
                id: o,
            }
            varietyService.removeBindingPro(idGroup).then(function(json) {
                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    $route.reload();
                }
            })
        }
    }
}]);
faApp.controller('SameProductDetailCtrl', ['$scope', '$timeout','$filter', '$sce', '$location', '$controller', '$route', '$routeParams', 'varietyService', function($scope, $timeout,$filter, $sce, $location, $controller, $route, $routeParams, varietyService) {
    $controller('BaseCtrl', {
        $scope: $scope
    });
    $scope.type = $routeParams.type;
    $scope.proId = {
        'fetchPId': $routeParams.fetchId,
        'pId': $routeParams.pId,
        'bindId': $routeParams.bindId
    }
    $scope.$watch('proId', function() {
        varietyService.getNewProInfo($scope.proId['fetchPId']).then(function(json) {
            $scope.detail = json.fpdto;
            $scope.detail.productAnnual = $sce.trustAsHtml($scope.detail.productAnnual)
        })
        varietyService.getSfaProInfo($scope.proId['pId']).then(function(json) {
            $scope.info = json.project;
            $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
            $scope.projectRabateList = json.projectRabateList;
        })
    }, true);
    $scope.addInfo = [];
    $scope.showAdd = function() {
        // $scope.addOther = true;
        $scope.item = {
            addOther : true,
            pStartAmount: '',
            pEndAmount: '',
            pAnnualRevenueExpect: '',
            pRabateProfit: ''
        }
        $scope.addInfo.push($scope.item);
        console.log($scope.addInfo);
    }
    $scope.infoDelete = function(index) {
        $scope.addInfo.splice(index,1);
        console.log($scope.addInfo);
    }

    //保存功能
    $scope.save = function() {

        $scope.formData = {
            pId: [],
            pRebateType: [],
            pStartAmount: [],
            pEndAmount: [],
            pAnnualRevenueExpect: [],
            pIsAgreement: [],
            pRabateProfit: [],
            pCorePrice: [],
            pCostPrice: [],
            pSellingPrice: [],
            pCostBackPrice: [],
            pCoreBackPrice: [],
            pBackSellingPrice: [],
            pBackRabateProfit: []
        };
        angular.forEach($scope.projectAnnualRevenue, function(o, i) {
            $scope.formData['pId'].push(o['pId']);
            $scope.formData['pRebateType'].push("01");
            $scope.formData['pStartAmount'].push(o['pStartAmount']);
            $scope.formData['pEndAmount'].push(o['pEndAmount']);
            $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
            $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
            $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
            $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
            $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);
            $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
            $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
            $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);
            $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);

            $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
        });       
        if ($scope.addInfo.length) {
            var isNull = false; 
            $('.addAd .nokong').each(function(){
                if( !$(this).val() ) {
                    isNull = true;
                }
            })
            if ( isNull ) {
                alert('请填写完整表单');
                return;
            } else {
                alert($scope.addInfo.length);
                for (var i = 0;i<$scope.addInfo.length; i++) {                   
                    $scope.formData['pId'].push($routeParams.pId);
                    $scope.formData['pRebateType'].push("01");
                    $scope.formData['pStartAmount'].push($scope.addInfo[i].pStartAmount);
                    $scope.formData['pEndAmount'].push($scope.addInfo[i].pEndAmount);
                    $scope.formData['pAnnualRevenueExpect'].push($scope.addInfo[i].pAnnualRevenueExpect);
                    $scope.formData['pRabateProfit'].push($scope.addInfo[i].pRabateProfit);
                    $scope.formData['pCorePrice'].push(0);
                    $scope.formData['pCostPrice'].push(0);
                    $scope.formData['pSellingPrice'].push(0);
                    $scope.formData['pCostBackPrice'].push(0);
                    $scope.formData['pCoreBackPrice'].push(0);
                    $scope.formData['pBackSellingPrice'].push(0);
                    $scope.formData['pBackRabateProfit'].push(0);
                    $scope.formData['pIsAgreement'].push(0);
                }
            }
        }
        $scope.formData2 = {
            id: $scope.info.id,
            fetchId: $scope.proId.fetchPId,
            pRecruitmentSummary: $scope.info.pRecruitmentSummary
        };
        for (k in $scope.formData) {
            $scope.formData2[k] = $scope.formData[k].join(",");
        }
        varietyService.updataProInfo($scope.formData2).then(function(json) {
            if (json.statusCode) {
                alert("出错了:" + json.statusCode);
            } else {
                alert('修改成功');
                $route.reload();
            }
        });
    };
    //删除功能
    $scope.deleteItem = function(v) {
        if ($scope.projectRabateList.length <= 1) {
            alert("最后一个不能删除");
            return;
        }

        $scope.projectAnnualRevenue.splice(v, 1);
        $scope.projectRabateList.splice(v, 1);

        $timeout(function() {
            $scope.save();
        }, 10);
    };
    //标记为不同产品
    $scope.markDiff = function() {
        if ( confirm('确定为不同产品') ) {        
            var idGroup = {
                id: $scope.proId.bindId
            }
            varietyService.removeBindingPro(idGroup).then(function(json) {
                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    $location.path('/varietyProduct/samePro').search({ type : $scope.type });
                }
            })
        }
    }
}]);
// faApp.controller('LikeProductListCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', function($scope,$location, $controller, $route, $routeParams) {
//     $controller('BaseListCtrl', {
//         $scope: $scope
//     });
//     $scope.$watch('config', function() {
//         console.log($scope.config);
//     }, true);
//     alert(2);
// }]);
faApp.controller('NewProductListCtrl', ['$scope', '$location', '$controller', '$route', '$routeParams', 'varietyService', function($scope, $location, $controller, $route, $routeParams, varietyService) {
    $controller('BaseListCtrl', {
        $scope: $scope
    });
    $scope.config.productSource = "1caifu"; //设置壹财富来源
    $scope.config.pType = $routeParams.type;
    $scope.config.pageSize = 10;
    $scope.$watch('config', function() {
        varietyService.getNewProList($scope.config).then(function(json) {
            $scope.list = json.list;
            $scope.pager = json.fnProductDto; //设置分页

        })
    }, true);
}]);
faApp.controller('NewProductDetailCtrl', ['$scope', '$sce', '$location', '$controller', '$route', '$routeParams', 'varietyService', function($scope, $sce, $location, $controller, $route, $routeParams, varietyService) {

    $scope.myUrl = '#/varietyProduct/add?t=' + $routeParams.type + '&fetid=' + $routeParams.id;
    $scope.NewProductId = $routeParams.id;
    $scope.$watch('NewProductId', function() {
        varietyService.getNewProInfo($scope.NewProductId).then(function(json) {
            $scope.detail = json.fpdto;
            $scope.detail.productAnnual = $sce.trustAsHtml($scope.detail.productAnnual);
        })
    }, true);
    $scope.showEstablishaFormFlag = false;
    $scope.changeStatus = function() {
            $scope.showEstablishaFormFlag = true;
        }
        //请求sfa未绑定产品
    $scope.type = $routeParams.type;
    var proType = $routeParams.type; //信托或者资管类型
    varietyService.noBindingProList(proType).then(function(json) {
            $scope.list = json.noBindProjectList;
        })
        //放弃该产品
    $scope.giveUpThisPro = function(id) {
        if ( confirm('确定放弃该产品') ) {
            varietyService.giveUpFetchingPro(id).then(function(json) {
                if (json.statusCode) {
                    alert('出错了' + json.statusCode)
                } else {
                    $location.path('/varietyProduct/newPro').search({
                        type: $routeParams.type
                    })
                }
            })
        }
    }
        //增加绑定关系
    $scope.addBinding = function() {
        $scope.proId = {
            'fetchPId': $scope.detail.id,
            'pId': $scope.selfPro,
            'associationType': 1
        }
        varietyService.addBindingPro($scope.proId).then(function(json) {
            if (json.statusCode) {
                alert('出错了' + json.statusCode)
            } else {
                $scope.showEstablishaFormFlag = false;
                // $location.url('/varietyProduct/samePro?type='+$routeParams.type);
                parent.location.reload() //iframe 上级页面刷新
            }
        })
    }
}]);
faApp.controller('addsNewProductCtrl', ['$scope', 'varietyService', 'productService', 'reportService', '$location', '$controller', '$route', '$routeParams', function($scope, varietyService, productService, reportService, $location, $controller, $route, $routeParams) {
    $controller('ProductAddCtrl', {
        $scope: $scope
    });
    $scope.product.fetchId = $routeParams.fetid;
    $scope.infoSave = function() {
        if (!$scope.form.$invalid) {
            $scope.selectTjzls = [];
            var flag = false;
            for (var i in $scope.allTjzls) {
                if ($scope.allTjzls[i]) {
                    flag = true;
                    $scope.selectTjzls.push(i);
                }
            }
            if (!flag) {
                alert("请勾选提交资料");
                return;
            }
            $scope.product.id = "";
            $scope.product.pType = $scope.t;
            //$scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
            $scope.product.pIssuingScale = 0;

            $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
            $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
            $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
            if ($scope.t != undefined && $scope.t == "02") {
                $scope.product.pInvestOwnerId && ($scope.product.pInvestOwner = $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName']);
            }
            $scope.product.pInvestOwnerId = $scope.product.pInvestOwnerId || -1;
            if ($scope.product.pInvestOwnerId == -1 && $scope.t == "02") {
                $scope.product.pInvestOwner = "";
            }

            if ($scope.ct && $scope.report.id) {
                $scope.product.copyType = "01";
            }

            $scope.product.tjzls = $scope.selectTjzls.join(",");

            varietyService.addNewPro($scope.product).then(function(json) {
                if (json.statusCode) {
                    alert("出错了:" + json.statusCode);
                } else {
                    alert("产品录入成功!");
                    var e_url = '/product/edit?id='+json.projectDTO.id+'&t='+$scope.t;
                    parent.parent.location.href =  e_url ;//跳转到编辑页面
                }
            });
        } else {
            if ($scope.product.pSummary == undefined || !$scope.product.pSummary) {
                alert("请填写产品简介");
            } else alert("请完整填写表单");
        }
    };
}]);
faApp.controller('BankListCtrl',['$scope','withdrawService','$location','$controller','$route',function($scope,withdrawService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

}]);

faApp.controller('WithdrawListCtrl',['$scope','withdrawService','$location','$controller','$route',function($scope,withdrawService,$location,$controller,$route) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.list = [];

	$scope.$watch('config',function(){
    withdrawService.withdrawList($scope.config).then(function(json){
      $scope.list = json.list || [];
      $scope.pager = json.pager;
    });
  },true);

	$scope.config = {
		"pageSize" : 20,
		"pageNo" : 1,
		"loginName" : '',
	};

  $scope.searchMap = {
		"loginName" : '', 
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };
  
	$scope.pageChanged = function(){
		$scope.config.pageNo = $scope.pager.pageNo;
	};

}]);


faApp.controller('WithdrawViewCtrl',['$scope','withdrawService','$location','$controller','$route','$routeParams',function($scope,withdrawService,$location,$controller,$route,$routeParams) {   
	$controller('BaseCtrl', {$scope: $scope}); 

  $scope.id = $routeParams.id;
  $scope.item = {id:$scope.id};
  $scope.withdraw = {};

  withdrawService.withdrawQuery($scope.id).then(function(json){
    $scope.withdraw = json.dto; 
  });

  $scope.save = function(){
    if (!$scope.form.$invalid){
      withdrawService.withdrawEdit($scope.item).then(function(json){
        if (!json.statusCode){
          $scope.alertNextPage("操作成功");
          $location.path("/withdraw/list");
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
}]);

angular.module('faApp')
  .service('activityService', [ 'ajaxService',function (ajaxService) {

    this.activityAdd = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ACTIVITY_ADD"), activity || {});
    };

    this.activityEdit = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ACTIVITY_EDIT"), activity || {});
    };

    this.activityList = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ACTIVITY_LIST"), activity || {});
    };

    this.activityById = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ACTIVITY_BY_ID"), activity || {});
    };

    this.activityNameList = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ACTIVITY_NAME_LIST"), activity || {});
    };

    
}]);
angular.module('faApp')
  .service('adService', [ 'ajaxService',function (ajaxService) {

    this.adList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("AD_LIST"),cfg || {});
    };  

    this.adRecommendList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("AD_RECOMMEND_LIST"),cfg || {});
    };  
    
    this.adAdd = function (ad) {
      return ajaxService.post(ajaxService.getApiUri("AD_ADD"),ad || {});
    };     

    this.adEdit = function (ad) {
      return ajaxService.post(ajaxService.getApiUri("AD_EDIT"),ad || {});
    };  

    this.adQuery = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("AD_QUERY"),{advertId:id});
    };  

    this.adStart = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("AD_EDIT"),cfg || {});
    };  

    this.adStop = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("AD_EDIT"),cfg || {});
    };  

    this.msgList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("MSG_LIST"), cfg || {});
    };

    this.msgDetail = function (id) {
      return ajaxService.post(ajaxService.getApiUri("MSG_DETAIL"), {id : id});
    };

    this.msgDelete = function (id) {
      return ajaxService.post(ajaxService.getApiUri("MSG_DELETE"), {id : id});
    };

    this.msgAdd = function (msg) {
      return ajaxService.post(ajaxService.getApiUri("MSG_ADD"), msg || {});
    };

    this.msgUpdate = function (msg) {
      return ajaxService.post(ajaxService.getApiUri("MSG_UPDATE"), msg || {});
    };

    this.actList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ACT_LIST"), cfg || {});
    };
    this.actPerList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ACT_PER_LIST"), cfg || {});
    };
    this.actDetail = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("ACT_DETAIL"), {id : id});
    };

    this.actAdd = function (act) {
      return ajaxService.post(ajaxService.getApiUri("ACT_ADD"), act || {});
    };

    this.actUpdate = function (act) {
      return ajaxService.post(ajaxService.getApiUri("ACT_UPDATE"), act || {});
    };
}]);
angular.module('faApp')
    .service('ajaxService', ['$http','$location','$q',function ($http,$location,$q) {
		var that = this;
    
    this.export = function(apiUrl,data){
      var url = this.url(apiUrl,data,1);
      location.href = url;
    };

		this.post = function(apiUrl,data){
			var d = $q.defer();
			delete data['createDate'];
			delete data['updateDate'];
			delete data['createBy'];
			delete data['updateBy'];
      delete data['callback'];
			$http.post(this.url(apiUrl,{},1), data).success(function(json){
				if (json.status == "NEED_LOGIN"){
					//$location.path("/login");
                    window.parent.parent.location.href="/login";
					return;
				}else if (that.isSysException(json.statusCode)){
					
				}else if (that.isPermissionDeny(json.statusCode)){
					//$location.path("/system/403");
                    // window.parent.location.href="/system/403";
                    alert("没有权限,联系管理员!");
                     return;
				}else{
					if (!that.isSuccessCode(json.statusCode)){
						json.attribute.statusCode = json.statusCode;
					}
					d.resolve(json.attribute);
				}
			}) .error(function(error){
				d.reject(error);
			});

			return d.promise;
		};

		this.jsonp = function(apiUrl,data){
			var delay = $q.defer(),
				url = this.url(apiUrl,data);
			$http.jsonp(url,{withCredentials: true}).success(function(json){
				if (json.status == "NEED_LOGIN"){
					//$location.path("/login");
                    window.parent.parent.location.href="/login";
					return;
				}else if (that.isSysException(json.statusCode)){
					
				}else if (that.isPermissionDeny(json.statusCode)){
					//$location.path("/system/403");
                   // window.parent.location.href="/system/403";
                   alert("没有权限,联系管理员!");
                     return;
				}else{
					if (!that.isSuccessCode(json.statusCode)){
						json.attribute.statusCode = json.statusCode;
					}
					delay.resolve(json.attribute);
				}
			}).error(function(data,status){
				delay.reject(data);
			});
			return delay.promise;
		};

		this.isSuccessCode = function(code){
			return code == "0000";
		};

		this.isSysException = function(code){
			return code == "3001";
		};

		this.isRenameError = function(code){
			return code == "2009";
		};

		this.isPasswordError = function(code){
			return code == "2009";
		};
		this.isDisableUserError = function(code){
			return code == "2013";
		};
		this.isPermissionDeny = function(code){
			return code == "0006";
		};

		this.url = function(apiUrl,data,isNotJsonp){
			var data = data || {};
			if (!isNotJsonp) data['callback'] = 'JSON_CALLBACK';

			delete data['createDate'];
			delete data['updateDate'];
			delete data['createBy'];
			delete data['updateBy'];

			var query = [];
			angular.forEach(data,function(v,i){
				query.push(i + "=" + encodeURI(data[i]));	
			});
			return App.apiHost + apiUrl + "?" + query.join("&");
		};

		this.getApiUri = function(k){
			var map = { 
        "LOGIN" : "/login.shtml",
        "UPDATELOGININFO" : "/updateLoginInfo.shtml",
        "LOGIN_STATUS" : "/queryLoginStatus.shtml",
        "LOGOUT" : "/logout.shtml",

        "AD_LIST" : "/advert/queryAdvertList.shtml",
        "AD_RECOMMEND_LIST" : "/advert/queryAdvertRecommendList.shtml",
        "AD_ADD" : "/advert/addAdvert.shtml",
        "AD_EDIT" : "/advert/updateAdvert.shtml",
        "AD_QUERY" : "/advert/queryAdvertInfo.shtml",

        "FA_LIST" : "/fa/queryFaUserList.shtml",
        "FA_EDIT" : "/fa/updateFaUser.shtml",
        "FA_QUERY" : "/fa/queryFaUser.shtml",
        "FA_SHOPQUERY" : "/fa/queryShopFaUser.shtml",
        "FA_UPDATE_CERT" : "/fa/updateFaUserForAudit.shtml",
        "FA_UPDATE_SHOPCERT" : "/fa/updateShopFaUserForAudit.shtml",
        "FA_UPDATE_CERTIMG" : "/fa/updateFaUserCert.shtml",
        "FA_QUERY_CERT" : "/fa/queryFaUserForAudit.shtml",
        "FA_BLACK_LIST" : "/blacklist/queryBlacklist.shtml",
        "FA_BLACK_ADD" : "/blacklist/addBlacklist.shtml",
        "FA_BLACK_QUERY" : "/blacklist/queryBlacklistDetail.shtml",
        "FA_SBDSTAT" : "/fa/queryFaUserListAuthPass.shtml",
        "FA_SBDLIST" : "/fa/querySingleFaUserListAuthPass.shtml",
        "FA_SBD_EXPORT" : "/fa/faUserAuthPassCsv.shtml",
        "FA_LIST_EXPORT" : "/fa/faUserCsv.shtml",
        "FA_USER_VISIT"  : "/fa/queryFaUserVisit.shtml",
        "FA_USER_VISIT_ADD" : "/fa/addFaUserVisit.shtml",
        "FA_USER_VISIT_DETAIL_ADD" : "/fa/updateFaUserForVisit.shtml",
        "FA_USER_VISIT_UPDATE" : "/fa/updateADFaUser.shtml",

        //内部理财师汇总统计
        "LCS_MAN_STATICTICS_LIST":"/shop/querylcsmanstatisticsList.shtml",
        //内部理财师汇总统计导出
        "LCS_MAN_STATICTICS_CSV":"/shop/lcsmanstatisticsCsv.shtml",
        // 查询内部理财师详情列表
        "LCS_MAN_DETAIL_LIST" : "/shop/querylcsmanDetailList.shtml",
        //导出内部理财师详情列表
        "LCS_MAN_DETAIL_CSV" : "/shop/lcsmanDetailCsv.shtml",
        //运营部门审核理财师权限--test
        "YUNYING_BUCHECK_FA":"/yunyingbucheckfa.shtml",

        "USER_LIST" : "/queryAllUser.shtml",
        "USER_LISTTREE" : "/listTree.shtml",
        "USER_ADD" : "/addUser.shtml",
        "USER_EDIT" : "/updateUserInfo.shtml",
        "USER_QUERY" : "/queryUserInfo.shtml",

        "LINK_LIST" : "/fl/queryList.shtml",
        "LINK_ADD" : "/fl/addFl.shtml", 
        "LINK_EDIT" : "/fl/updateFl.shtml",
        "LINK_QUERY" : "/fl/queryFl.shtml",
        "LINK_DELETE" : "/fl/deleteFl.shtml",

        "PRODUCT_LIST" : "/product/queryProjectListForPublish.shtml",
        "PRODUCT_ADD" : "/product/addProject.shtml",
        "PRODUCT_EDIT" : "/productUpdate/updateProjectBaseInfo.shtml",
        "PRODUCT_DELETE" : "/productUpdate/deleteProject.shtml",
        "PRODUCT_SET" : "/product/productSet.shtml",
        "PRODUCT_PUBLISH" : "/product/updateProjectForPublish.shtml",
        "PRODUCT_VERIFY" : "/product/updateProjectForVerify.shtml",
        "PRODUCT_QUERY" : "/product/queryProjectForPublish.shtml",
        //渠道查询产品详情
        "QD_PRODUCT_QUERY" : "/product/queryProductQDDetail.shtml",
        "PRODUCT_UPDATE_SALEPROCESS" : "/product/projectAllSubscription.shtml",
        "PRODUCT_UPDATE_Recruitment" : "/productUpdate/changepRecruitmentSummary.shtml",
        "PRODUCT_RECOMMEND" : "/product/addProductRecommend.shtml",
        "PRODUCT_PROFIT_LIST" : "/productUpdate/queryUpdateProjectAnnualRevenue.shtml",
        "PRODUCT_PROFIT_LOG_LIST" : "/product/annualRevenueRebateLog.shtml",
        "PRODUCT_PROFIT_UPDATE" : "/productUpdate/updateProjectAnnualRevenue.shtml",
        "PRODUCT_ATTACH_LIST" : "/productUpdate/queryProjectAttachments.shtml",
        "PRODUCT_ATTACH_UPDATE" : "/productUpdate/updateProjectAttachments.shtml",
        "PRODUCT_TRANS_LIST" : "/product/transferHisQueryList.shtml",
        "PRODUCT_TRANS_ADD" : "/product/transferHisAdd.shtml",
        "PRODUCT_SEND_EMAIL" : "/product/sendConfirmEmail.shtml",
        //产品列表 PEVC
        "QUERY_PRODUCT_LIST":"/product/queryProductList.shtml",
        "UPDATE_PRODUCT_DETAIL":"/productUpdate/updateProduct.shtml",
        "ADD_PRODUCT_DETAIL":"/product/addProduct.shtml",
        //产品新增或者价格变动   提交审核
        "PRODUCT_ADD_CHECK":"/product/projectAddCheck.shtml",
        "PRODUCT_NOTICE_QUERY": "/fpFileRecord/list.shtml",
        "PRODUCT_NOTICE_DELETE": "/fpFileRecord/delete.shtml",
        "PRODUCT_SERIES_ADD": "/product/productSeriesAdd.shtml",
        "PRODUCT_SERIES_LIST": "/product/fpProjectSeriesList.shtml",
        "PRODUCT_SERIES_DELETE": "/product/fpProjectSeriesDelete.shtml",
        "PRODUCT_SEARCHNO_RECORD_LIST": "/product/searchnorecordlist.shtml",
        //根据名字分组查询所有产品
        "QUERY_ALL_PRODUCT_BY_FULLNAME":"/product/queryAllProductByFullName.shtml",
         // 查询已存在分组   打款账户名 
        "QUERY_ALL_EXISTING_ACCOUNT":"/fpAccountVoucher/queryAllExistingAccount.shtml",
        //凭条列表
        "QUERY_FP_ACCOUNT_VOUCHER":"/fpAccountVoucher/listFpAccountVoucher.shtml",
        //凭条详情
        "QUERY_FP_ACCOUNT_VOUCHER_DETAIL":"/fpAccountVoucher/detailFpAccountVoucher.shtml",
                //凭条修改
        "QUERY_FP_ACCOUNT_VOUCHER_UPDATE":"/fpAccountVoucher/updateFpAccountVoucher.shtml",
        //凭条新增
        "QUERY_FP_ACCOUNT_VOUCHER_ADD":"/fpAccountVoucher/addFpAccountVoucher.shtml",
        // 查询已存在分组   凭条上传人
        "QUERY_ACCOUNT_VOUCHER_CRAETEBY":"/fpAccountVoucher/queryAccountVoucherCreateBy.shtml",

        //产品成立公告列表
        "QUERY_PRODUCT_NOTICE_LIST":"/productNotice/queryProductNotice.shtml",
        "QUERY_PRODUCT_NOTICE_DETAIL":"/productNotice/queryProductNoticeDetail.shtml",
        "EDIT_PRODUCT_NOTICE":"/productNotice/updateProductNotice.shtml",
        //外场产品
        "OUT_PRODUCT_LIST":"/outProduct/queryForegroundProductList.shtml",
        "OUT_PRODUCT_DETAIL":"/outProduct/queryForegroundProductDetail.shtml",
        //壹财富xpath配置
        "PRODUCT_REGEX_LIST":"/fpFetchProductRegex/queryAllProductRegex.shtml",
        "EDIT_PRODUCT_REGEX":"/fpFetchProductRegex/updateFetchProductRegex.shtml",
        //个人供应方列表
        "PERSONAL_SUPPLIER_LIST":"/outProduct/queryProductSupplierList.shtml",
        "PERSONAL_SUPPLIER_INFO":"/outProduct/queryProductSupplierInfo.shtml",
        "SAVE_PERSONAL_SUPPLIER":"/outProduct/saveProductSupplierInfo.shtml",
        "PERSONAL_SUPPLIER_LIST_CSV":"/outProduct/queryProductSupplierListCsv.shtml",
        "EDIT_OUT_PRODUCT_SUPPLIER":"/outProduct/editProductSupplier.shtml",
        "EDIT_OUT_PRODUCT":"/outProduct/editForegroundProduct.shtml",
        //发送邮件
        "SEND_OUT_PRODUCT_EMAIL":"/outProduct/sendOutProductEmail.shtml",

        //竞价产品
        "BID_PRODUCT_LIST":"/fpBiddingReceipt/queryFpBiddingReceipt.shtml",
        "BID_PRODUCT_DETAIL":"/fpBiddingReceipt/queryFpBiddingReceiptDetail.shtml",
        "BID_PRODUCT_DTATUS":"/fpBiddingReceipt/checkBiddingStatus.shtml",


        "COMPANY_LIST" : "/projectCompany/listProjectCompany.shtml",
        "COMPANY_ADD" : "/projectCompany/addProjectCompany.shtml",
        "COMPANY_EDIT" : "/projectCompany/updateProjectCompany.shtml",
        "COMPANY_QUERY" : "/projectCompany/queryProjectCompanyView.shtml",
        "COMPANY_DELETE" : "/projectCompany/deleteProjectCompany.shtml",
        "COMPANY_SUB_LIST" : "/infoSubscribe/listInfoSubscribe.shtml",

        "OPERATION_STAT_COUNT" : "/queryCountInfo.shtml",
        //我的业绩,团队业绩
        "queryOrderOwnerUserCountAmount":'/order/queryOrderOwnerUserCountAmount.shtml',
        //用户访问详情
        "queryVistDetail":'/queryVistDetail.shtml',
        //关注客户
        "customerFocus":'/customerFocus.shtml',
        //待办事项列表
        "listFaRevisitTask":"/faRevisitTask/listFaRevisitTask.shtml",
        //标记已完成接口
        "updateFaRevisitTask":"/faRevisitTask/updateFaRevisitTask.shtml",

        "WITHDRAW_LIST" : "/withdraw/queryAccountWithdraw.shtml",
        "WITHDRAW_QUERY" : "/withdraw/queryAccountWithdrawDetail.shtml",
        "WITHDRAW_EDIT" : "/withdraw/updateWithdrawStatus.shtml",

        "FISS_LIST" : "/queryFissInfo.shtml",
        "TOOLS_UPLOAD" : "/fileUpload.shtml",

        "ROLE_LIST" : "/group/queryGroup.shtml",
        "ROLE_ADD" : "/group/addGroup.shtml",
        "ROLE_EDIT" : "/group/updateGroupInfo.shtml",
        "ROLE_QUERY" : "/group/queryGroupInfo.shtml",

        "URL_LIST" : "/group/actionList.shtml",
        "URL_ADD" : "/action/addAction.shtml", 
        
        "SIMU_VIDEO_LIST" : "/productVideo/queryProductVideoInfo",
        "SIMU_VIDEO_EDIT" : "/productVideo/updateProductVideoInfo",

        "SIMU_LIST" : "/fund/fpFundInfoQueryList.shtml",
        "SIMU_ADD" : "/fund/fpFundInfoAdd.shtml",
        "SIMU_EDIT" : "/fund/fpFundInfoUpdate.shtml",
        "SIMU_QUERY" : "/fund/fpFundInfoDetail.shtml",
        "SIMU_REMOVE" : "/fund/fpFundInfoDelete.shtml",
        "SIMU_QUERY_FUNDCODE":"/fund/fpFundInfoCode.shtml",
        
        "SIMU_BUYHIS_LIST" : "/fund/fdAwkwardnessQueryList.shtml",
        "SIMU_BUYHIS_ADD" : "/fund/fdAwkwardnessAdd.shtml",
        "SIMU_BUYHIS_EDIT" : "/fund/fdAwkwardnessUpdate.shtml",
        "SIMU_BUYHIS_QUERY" : "/fund/fdAwkwardnessDetail.shtml",
        "SIMU_BUYHIS_REMOVE" : "/fund/fdAwkwardnessDelete.shtml",

        "SIMU_BUYINFO_LIST" : "/fund/fdBuynoticeQueryList.shtml",
        "SIMU_BUYINFO_ADD" : "/fund/fdBuynoticeAdd.shtml",
        "SIMU_BUYINFO_EDIT" : "/fund/fdBuynoticeUpdate.shtml",
        "SIMU_BUYINFO_QUERY" : "/fund/fdBuynoticeDetail.shtml",
        "SIMU_BUYINFO_REMOVE" : "/fund/fdBuynoticeDelete.shtml",

        "SIMU_COMPANY_LIST" : "/fund/fdCompanyQueryList.shtml",
        "SIMU_COMPANY_ADD" : "/fund/fdCompanyAdd.shtml",
        "SIMU_COMPANY_EDIT" : "/fund/fdCompanyUpdate.shtml",
        "SIMU_COMPANY_QUERY" : "/fund/fdCompanyDetail.shtml",
        "SIMU_COMPANY_REMOVE" : "/fund/fdCompanyDelete.shtml",

        "SIMU_MANAGER_LIST" : "/fund/fdManagerQueryList.shtml",
        "SIMU_MANAGER_ADD" : "/fund/fdManagerAdd.shtml",
        "SIMU_MANAGER_EDIT" : "/fund/fdManagerUpdate.shtml",
        "SIMU_MANAGER_QUERY" : "/fund/fdManagerDetail.shtml",
        "SIMU_MANAGER_REMOVE" : "/fund/fdManagerDelete.shtml",
        
        "SIMU_ORDER_LIST" : "/order/queryOrderTmpList.shtml",
        "SIMU_ORDER_PROID_LIST":"/order/queryOrderTmpByProductList.shtml",
        "SIMU_ORDER_EDIT" : "/order/updateOrderTmp.shtml",

        "SIMU_PRODUCT_RECOMMEND" : "/order/addProductRecommend.shtml",
        
        "MILLION_LIST" : "/activities/queryActivitiesMollionsWealth.shtml",
        "MILLION_ADD" : "/activities/addActivitiesMollionsWealth.shtml",
        "MILLION_EDIT" : "/activities/updateActivitiesMollionsWealth.shtml",
        "MILLION_REMOVE" : "/activities/deleteActivitiesMollionsWealth.shtml",

        "ACTIVITY_ADD" : "/projectActivities/addProjectActivities.shtml",
        "ACTIVITY_EDIT" : "/projectActivities/updateProjectActivities.shtml",
        "ACTIVITY_LIST" : "/projectActivities/queryProjectActivities.shtml",
        "ACTIVITY_NAME_LIST" : "/projectActivities/queryProjectActivitiesNameList.shtml",
        "ACTIVITY_BY_ID" : "/projectActivities/detailProjectActivities.shtml",

        "ROADVIDEO_ADD" : "/fpVideo/addFpVideo.shtml",
        "ROADVIDEO_EDIT" : "/fpVideo/updateFpVideo.shtml",
        "ROADVIDEO_LIST" : "/fpVideo/listFpVideo.shtml",
        "ROADVIDEO_BT_ID" : "/fpVideo/detailFpVideo.shtml",
        "ROADVIDEO_DELETE" : "/fpVideo/deleteFpVideo.shtml",
        "ROADVIDEO_PRO_BY_ID" : "/fpVideo/queryVideoInfo.shtml",
        "ROADVIDEO_PASSWORD" : "/fpVideo/updateFpVideoPassword.shtml",

        "ORDER_LIST" : "/order/queryOrderList.shtml",
        "ORDER_PROID_LIST":"/order/queryOrderByProIdList.shtml",
        "ORDER_QUERY" : "/order/queryOrderDetail.shtml",
        "ORDER_EDIT_STATUS" : "/order/updateOrderStatus.shtml",
        "ORDER_EDIT_DEFRIENDSTATUS" : "/order/updateOrderDefriendStatus.shtml",

        //订单合同详情
        "ORDER_CONTRACT_DETAIL" : "/fpFaUserContract/findFaUserContract.shtml",
        //订单合同编辑新增
        "ORDER_CONTRACT_EDIT" : "/fpFaUserContract/saveFaUserContract.shtml",
        //订单详情by lisu
        "ORDER_DTAIL" : "/order/orderDetail.shtml",

        "ORDER_PHO_DETAIL":"/orderpho/orderPhoDetail.shtml",
        "UPDATE_ORDER_PHO":"/orderpho/updateOrderPho.shtml",
        "ADD_ORDER_PHO":"/orderpho/addOrderPhoData.shtml",
        "ADD_ORDER_PEVC_PHO":"/orderpho/addOrderPhoDataByPE.shtml",
        "M2B_WIN_LIST" : "/activities/queryActivitiesWinList.shtml",
        
        "SUPPLIER_LIST" : "/projectSupplier/listProjectSupplier.shtml",
        "SUPPLIER_FLOW_LIST" : "/projectSupplier/listProjectSupplierFlow.shtml",
        "SUPPLIER_DETAIL" : "/projectSupplier/queryProjectSupplierView.shtml",
        "SUPPLIER_ADD" : "/projectSupplier/addProjectSupplier.shtml",
        "SUPPLIER_EDIT" : "/projectSupplier/updateProjectSupplier.shtml",
        
        "STATISTICAL_ORDER_LIST" : "/queryOrderDetailedList.shtml",
        "STATISTICAL_USER_LIST" : "/queryAuthUserDetailedList.shtml",
        "STATISTICAL_ORDER_LIST_CSV" : "/queryOrderDetailedListCsv.shtml",
        "STATISTICAL_USER_LIST_CSV" : "/queryAuthUserDetailedListCsv.shtml",
        
        "MESSAGE_MANAGER_LIST" : "/sms/smsADList.shtml",
        "MESSAGE_MANAGER_EDIT" : "/sms/updateSMSAD.shtml",

        "REPORT_DETAIL" : "/product/deepAnalyticsDetail.shtml",
        "REPORT_SAVE"   : "/product/deepAnalyticsSave.shtml",

        "MSG_LIST" : "/news/queryMsgList.shtml",
        "MSG_ADD" : "/news/addMsg.shtml",
        "MSG_DETAIL" : "/news/newsDetail.shtml",
        "MSG_UPDATE" : "/news/updateMsg.shtml",
        "MSG_DELETE" : "/news/deleteMsg.shtml",

        "ACT_LIST" : "/activities/queryActList.shtml",
        "ACT_PER_LIST" : "/activities/activitiesNowPerson.shtml",
        "ACT_DETAIL" : "/activities/queryPublicActivitieDetail.shtml",
        "ACT_ADD" : "/activities/addAct.shtml",
        "ACT_UPDATE" : "/activities/updatePublicActivities.shtml",

        "INFO_MANAGE_FEED_BACK" : "/fpUserFeedBack/fpUserFeedBackList.shtml",
        "INFO_MANAGE_BANK_CARD" : "/bank/queryBankCard.shtml",
        "INFO_MANAGE_WITHDRAW" : "/withdraw/queryAccountWithdraw.shtml",
        "INFO_MANAGE_ASKFIR_LIST" : "/withdraw/wallettWithdrawList.shtml",
        "INFO_MANAGE_ASKFIR_DETAIL" : "/withdraw/wallettWithdrawDetail.shtml",
        "INFO_MANAGE_ASKFIR_FAIL" : "/withdraw/wallettWithdrawFail.shtml",
        "INFO_MANAGE_ASKFIR_SUCCESS" : "/withdraw/wallettWithdrawSuccess.shtml",
        "INFO_MANAGE_WITHDRAW_DETAIL" : "/withdraw/queryAccountWithdrawDetail.shtml",
        "INFO_MANAGE_WITHDRAW_UPDATE" : "/withdraw/updateWithdrawStatus.shtml",
        "INFO_MANAGE_PARRINNING_LIST" : "/payment/queryPaymentList.shtml",

        "SWITCH_LIST" : "/switch/querySwitch.shtml",
        "SWITCH_UPDATE" : "/switch/updateSwitch.shtml",

        "API_SETTING_LIST" : "/webApi/queryApiSetting.shtml",
        "API_SETTING_UPDATE" : "/webApi/updateApiSetting.shtml",

        "ORDER_MANAGER_USER_LIST" : "/order/queryOrderManagerUsersList.shtml",
        "NOT_ORDER_MANAGER_USER_LIST" : "/order/queryNotOrderManagerUserList.shtml",
        "ORDER_MANAGER_USER_ADD" : "/order/orderManagerUserAdd.shtml",
        
        "MANAGER_ORDER_USER_ADD" : "/managerOrder/addManagerOrderUser.shtml",
        "MANAGER_ORDER_USER_UPDATE" : "/managerOrder/updateManagerOrderUser.shtml",
        "MANAGER_ORDER_UPDATE_BY_USER" : "/managerOrder/editManagerOrderByUser.shtml",

        "ORDER_FOLLOW_UP_LIST" : "/order/orderReminder.shtml",

        "LICAISHI_MANAGER_USER_LIST" : "/licaishi/queryLicaishiManagerUsersList.shtml",
        "LICAISHI_MANAGER_USER_LIST_OTHER" : "/licaishi/queryLicaishiManagerUsersListForAdviser.shtml",
        "NOT_LICAISHI_MANAGER_USER_LIST" : "/licaishi/queryNotLicaishiManagerUserList.shtml",
        "LICAISHI_MANAGER_USER_ADD" : "/licaishi/licaishiManagerUserAdd.shtml",
        "MANAGER_LICAISHI_USER_ADD" : "/managerLicaishi/addManagerLicaishiUser.shtml",
        "MANAGER_LICAISHI_HUISHOU_BY_USER":"/managerLicaishi/editManagerLicaishiByUser.shtml",

        "FA_MARK_FA_USER" : "/fa/makeCompanyUser.shtml",
        //多平台抓取产品列表
        "EXTERIOR_FETCH__PRO_LIST" : "/fetchProduct/newProductList.shtml", //未匹配SFA产品列表
        "EXTERIOR_FETCH__PRO_DETAIL" : "/fetchProduct/newProductDetail.shtml", //新产品详情
        "NO_BINDING_FETCH__PRO_LIST" : "/fetchProduct/noBindProjectList.shtml", //未绑定的SFA产品列表
        "YES_BINDING_FETCH__PRO_LIST" : "/fetchProduct/bindProjectList.shtml", //已绑定的SFA产品列表
        "REMOVE_BINDING" : "/fetchProduct/unbindProduct.shtml", //解除绑定关系
        "ADD_BINDING" : "/fetchProduct/addFpRelevance.shtml", //新增抓取产品和SFA产品绑定
        "GIVEUP_PRO_CAPTURE" : "/fetchProduct/deleteNewProduct.shtml", //放弃抓取产品
        "SFA__PRO_DETAIL" : "/fetchProduct/projectDetail.shtml", //SFA产品详情
        "UPDATE__PRO_DETAIL" : "/fetchProduct/updateProjectByFetch.shtml", //更新产品信托募集
        "ADD_FETCH_PRO" : "/fetchProduct/addProjectByFetch.shtml", //根据壹财富新增产品
        
        //线下活动名单
        "DOWNLINE_LIST" : "/offlineUser/queryOfflineUserList.shtml", 
        "DOWNLINE_ADD" : "/offlineUser/addOfflineUser.shtml", 
        "DOWNLINE_DETAIL" : "/offlineUser/queryOfflineUserInfo.shtml", 
        "DOWNLINE_UPDATA" : "/offlineUser/updateOfflineUser.shtml", 
        "DOWNLINE_UPFILE" : "/offlineUser/importOfflineUser.shtml", 
        "DOWNLINE_UPFILE_TU" : "/offlineUser/importOfflineUserConfirm.shtml", 
        //发送短信和待办事项
        "REVISIITTASK":"/faRevisitTask/addFaRevisitTask.shtml",
        "QUERYACTSOURCE":"/fa/queryActSource.shtml",


        //渠道产品展示
        "PRODUCT_QUDAO_LIST":"/product/queryProductQDList.shtml",
        
        //渠道查询个人订单
        "ORDER_QDM_LIST":"/order/queryQuDaoMyOrderListByGaiZao.shtml",

        //渠道查询所有订单
        "ORDER_QDA_LIST":"/order/queryQuDaoAllOrderListByGaiZao.shtml",

        //产品查询个人订单
        "ORDER_CPM_LIST":"/order/queryChanPinMyOrderListByGaiZao.shtml",

        //产品查询所有订单
        "ORDER_CPA_LIST":"/order/queryChanPinAllOrderListByGaiZao.shtml",

        //财务查询所有订单
        "ORDER_CWA_LIST":"/order/queryCaiWuAllOrderListByGaiZao.shtml",

        //产品负责人
        "PRODUCT_FZR_LIST":"/order/queryOrderOwnerUserList.shtml",

        //订单详情
        "ORDER_XIANGQING":"/order/queryOrderDetailByGaiZao.shtml",

        //订单修改
        "ORDER_CHANGE":"/order/updateOrderStatusByGaiZao.shtml",
        //20170731 订单流程改造 修改接口更新
        "ORDER_CHANGE_BY_STATUS":"/order/orderStatus.shtml",
        //财务订单详情
        "ORDER_CWA_VIEW":"/order/queryOrderAllDetailByGaiZao.shtml",

        //财务管理员
        "ORDER_CWA_GLY_LIST":"/order/queryCaiWuMyOrderListByGaiZao.shtml",

        // 热销产品
        "MEDIA_RECOMMEND_ADD" : "/recommentProduct/addRecommentProduct.shtml",
        "MEDIA_RECOMMEND_DELETE" : "/recommentProduct/delRecommentProduct.shtml",
        "MEDIA_RECOMMEND_LIST" : "/recommentProduct/queryRecommentProduct.shtml",

        //导出订单
        "ORDER_LIST_EXPORT" : "/order/orderCsv.shtml",

        "USER_BEHAVIOR_LIST" : "/action/toDataList.shtml",

        "USER_SAlECON_LIST" : "/querySalesPerformance.shtml",
        "USER_SAlECON_CVS" : "/querySalesPerformanceCsv.shtml",
        
        //妈妈桑接口
        "BLINDATE_LIST" : "/fpHdFinancingBlind/listFpHdFinancingBlind.shtml",
        "BLINDATE_UPDATA" : "/fpHdFinancingBlind/updateFpHdFinancingBlind.shtml",

        "HONGBAO_LIST":"/activitiesGroup/queryActivitiesGroupInfo.shtml",
        "HONGBAO_LIST_EXPORT":"/activitiesGroup/queryActivitiesGroupInfoCSV.shtml", 
        "HONGBAO_DETAIL":"/activitiesGroup/queActivitiesGroupDetail.shtml",
        "HONGBAO_JIHUO":"/activitiesGroup/activationGroup.shtml",

        // 三方公司 索引
        "SANFANG_QUERY":"/3rdProjectCompany/queryTPC.shtml",
        "SANFANG_UPDATE":"/3rdProjectCompany/updateTPC.shtml",
        "SANFANG_ADD":"/3rdProjectCompany/addTPC.shtml",
        "SANFANG_DELETE":"/3rdProjectCompany/deleteTPC.shtml",
        //机构搜索
        "JIGOU_QUERY":"/product/queryInvestOwner.shtml",

        // 消息推送
        "NEWS_ADD" : "/jPush/addjPushMessage.shtml",
        "NEWS_EDIT" : "/jPush/updatejPushMessage.shtml",
        "NEWS_DELETE" : "/jPush/deljPushMessage.shtml",
        "NEWS_LIST" : "/jPush/listjPushMessage.shtml",


        "FINANCIER_LIST" : "/fpProjectFinancier/listFpProjectFinancier",
        "FINANCIER_ADD" : "/fpProjectFinancier/addFpProjectFinancier",
        "FINANCIER_DELETE" : "/fpProjectFinancier/deleteFpProjectFinancier",

        "SHOP_USER_LIST" : "/shop/queryShopUserList.shtml",

        "SHOP_SUCAI_LIST" : "/shop/queryShopSucai.shtml",
        "SHOP_SUCAI_ADD" : "/shop/addShopSucai.shtml",

        "SHOP_BEHAVIOR_HOME_LIST" : "/shop/queryBehaviorHomeList.shtml",
        "SHOP_BEHAVIOR_PROD_LIST" : "/shop/queryBehaviorProdList.shtml",
        "SHOP_BEHAVIOR_CUST_LIST" : "/shop/queryBehaviorCustList.shtml",
        "SHOP_BEHAVIOR_FP_LIST" : "/shop/queryBehaviorFpList.shtml",
        "SHOP_BEHAVIOR_FOOTERMENU_LIST" : "/shop/queryBehaviorFooterMenuList.shtml",
        "SHOP_USER_FEED_BACK_LIST" : "/fpFaUserFeedback/listFpFaUserFeedback.shtml",
        "SHOP_USER_FEED_BACK_ADD" : "/fpFaUserFeedback/addFpFaUserFeedback.shtml",
        "ORDER_UPDATE_ORDER_DETAIL" : "/orderUpdate/queryOrderDateDetail.shtml",
        "ORDER_UPDATE_ORDER_EDIT":"/orderUpdate/updateOrderDateDetail.shtml",
        "ORDER_UPDATE_ORDER_SAVE":"/orderUpdate/saveOrderIdList.shtml",
        "ORDER_UPDATE_ORDER_QUERY":"/orderUpdate/getOrderIdList.shtml",
        "SHOP_BACK_GROUND_LIST":"/fpShopBackground/listFpShopBackground.shtml",
        "SHOP_BACK_GROUND_ADD":"/fpShopBackground/updateFpShopBackground.shtml",
        "SHOP_BEHAVIOR_CUSTREGISTER_LIST":"/shop/custregister.shtml",
        "SHOP_BEHAVIOR_CRUXDATA_LIST":"/shop/cruxdata.shtml",

        "SHOP_SUBJECT_ADD":"/fpShopSubject/addFpShopSubject.shtml",
        "SHOP_SUBJECT_UPDATE":"/fpShopSubject/updateFpShopSubject.shtml",
        "SHOP_SUBJECT_DELETE":"/fpShopSubject/deleteFpShopSubject.shtml",
        "SHOP_SUBJECT_LIST":"/fpShopSubject/listFpShopSubject.shtml",

        //数据统计-----
        // 月注册量
        "STATISTICS_FA_REGISTER_BY_MONTH": "/queryFaUserRegisterByMonthCount.shtml",
        // 审核中、审核失败、审核通过的人数
        "STATISTICS_FAUSER_ROLE_COUNT": "/queryFaUserRoleCount.shtml",
        // 总注册数
        "STATISTICS_REGISTER_ALL_COUNT": "/queryFaUserCount.shtml",
        // 月订单量 saleMonth销售月份     oAmount总金额   orderCount订单总数
        "STATISTICS_ORDER_BY_MONTH": "/queryOrderCountByMonth.shtml",
        // 认证用户的下单比例 noHasOrderUserCount没有订单的认证用户数   allUserCount所有的认证用户数
        "STATISTICS_ORDER_USER_PER": "/queryOrderUserPer.shtml",
        // 认证理财师role占比
        "STATISTICS_ORDER_FAUSER_ROLE_PROPORTION": "/queryOrderFaUserRoleProportion.shtml",
        // 认证理财师role占比
        "STATISTICS_ORDER_FAUSER_PROPORTION": "/queryFaUserRoleProportion.shtml",
        // 用户下单比例
        "STATISTICS_ORDER_USER_TOTAL": "/queryUserTotalSales.shtml",
        // 用户下单比例
        "STATISTICS_COMPANY_TOTAL": "/queryCommpanyTotal.shtml",

        //PC首页动态统计配置
        "PC_TOTAL_DYNAMIC":"/fpFaTotal/detailFpFaTotal.shtml",
        "PC_TOTAL_DYNAMIC_UPDATE":"/fpFaTotal/updateFpFaTotal.shtml",
        "PLAYOPEN_APPLY_LIST":"/fpShopPlayopenApply/listFpShopPlayopenApply.shtml",
        "PLAYOPEN_APPLY_EDIT":"/fpShopPlayopenApply/updateFpShopPlayopenApply.shtml",

        "SHOP_INFORMATION_ADD":"/fpShopInformation/addFpShopInformation.shtml",
        "SHOP_INFORMATION_EDIT":"/fpShopInformation/editFpShopInformation.shtml",
        "SHOP_INFORMATION_DELETE":"/fpShopInformation/deleteFpShopInformation.shtml",
        "SHOP_INFORMATION_DETAIL":"/fpShopInformation/detailFpShopInformation.shtml",
        "SHOP_INFORMATION_LIST":"/fpShopInformation/listFpShopInformation.shtml",
        "SHOP_INFORMATION_UPORDOWN":"/fpShopInformation/upordownFpShopInformation.shtml",

        //抽奖配置
        "USER_SALEPRIZES_DELETE":"/salesPrizes/deleteSalesPrizes.shtml",
        "USER_SALEPRIZES_ADD":"/salesPrizes/addBatchSalesPrizes.shtml",
        "USER_SALEPRIZESPEOPLE_ADD":"/salesPrizesPeople/addBatchSalesPrizesPeople.shtml",
        "USER_SALEPRIZES_LIST":"/salesPrizes/listSalesPrizes.shtml",
        "USER_SALEPRIZESPEOPLE_LIST":"/salesPrizesPeople/listSalesPrizesPeople.shtml",
        
        "SHOP_YXT_ACTIVITY_COUNT":"/shop/yxtActivity.shtml",
        "SHOP_YXT_ACTIVITY_DRAW":"/shop/yxtActivityDraw.shtml",
        "SHOP_YYZC_ACTIVITY_SHOPLIST":"/wxShopInfo/listWxShopInfo.shtml",
        "SHOP_YYZC_ACTIVITY_SHOPADD":"/wxShopInfo/addWxShopInfo.shtml",
        "SHOP_YYZC_ACTIVITY_SHOPDELETE":"/wxShopInfo/deleteWxShopInfo.shtml",
        "SHOP_YYZC_ACTIVITY_SHOPUPDATE":"/wxShopInfo/updateWxShopInfo.shtml",

        //未录入产品关键词查询
        "STATISTICS_PRODUCT_KEYWORD": "/xcxSearchnoRecord/listXcxSearchnoRecord",
        "STATISTICS_PRODUCT_KEYWORD_USER": "/xcxSearchnoRecord/listXcxSearchnoRecordUser",

        //未录入产品且未反馈，发送消息
        "STATISTICS_SEND_MSG":"/xcxNews/addXcxNews"

			};
			return map[k] || "";
		};

    }]);


angular.module('faApp')
    .service('authService', ['ajaxService', 'sessionService', function (ajaxService, sessionService) {

        this.roleList = function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("ROLE_LIST"), cfg || {});
        };
        this.roleAdd = function (role) {
            return ajaxService.post(ajaxService.getApiUri("ROLE_ADD"), role || {});
        };

        this.roleEdit = function (role) {
            return ajaxService.post(ajaxService.getApiUri("ROLE_EDIT"), role || {});
        };

        this.roleQuery = function (id) {
            return ajaxService.post(ajaxService.getApiUri("ROLE_QUERY"), {groupId: id});
        };

        this.urlList = function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("URL_LIST"), cfg || {});
        };

        this.urlAdd = function (item) {
            return ajaxService.post(ajaxService.getApiUri("URL_ADD"), item || {});
        };

        this.roleIsAuth = function (who) {
            var authFlag = false,
                groups = sessionService.getItem("user.groups") || "";
            if (who == "PRODUCT_CORE_PRICE") {
                if (groups.indexOf() != -1) {
                    authFlag = true;
                }
            }

            return authFlag;
        };

        this.getModule = function (url) {
            var map = {
                "addXcxNews":"shop",
                "listXcxSearchnoRecordUser":"shop",
                "listXcxSearchnoRecord":"shop",
                "updateWxShopInfo.shtml": "shop",
                "deleteWxShopInfo.shtml": "shop",
                "addWxShopInfo.shtml": "shop",
                "listWxShopInfo.shtml": "shop",
                "listFpShopPlayopenApply.shtml": "shop",
                "updateFpShopPlayopenApply.shtml": "shop",
                "detailFpFaTotal.shtml": "operation",
                "updateFpFaTotal.shtml": "operation",
                "yxtActivity.shtml": "shop",
                "yxtActivityDraw.shtml": "shop",
                "addFpShopInformation.shtml": "shop",
                "editFpShopInformation.shtml": "shop",
                "deleteFpShopInformation.shtml": "shop",
                "detailFpShopInformation.shtml": "shop",
                "listFpShopInformation.shtml": "shop",
                "upordownFpShopInformation.shtml": "shop",
                "querylcsmanDetailList.shtml": "fa",
                "querylcsmanstatisticsList.shtml": "fa",
                "deleteFpShopSubject.shtml": "shop",
                "updateFpShopSubject.shtml": "shop",
                "updateFpShopBackground.shtml": "shop",
                "listFpShopBackground.shtml": "shop",
                "addFpShopSubject.shtml": "shop",
                "listFpShopSubject.shtml": "shop",
                "addFpFaUserFeedback.shtml": "operation",
                "listFpFaUserFeedback.shtml": "operation",
                "queryBehaviorHomeList.shtml": "shop",
                "queryBehaviorFooterMenuList.shtml": "shop",
                "queryBehaviorProdList.shtml": "shop",
                "queryBehaviorCustList.shtml": "shop",
                "queryBehaviorFpList.shtml": "shop",
                "falist.html": "shop",
                "faauit.html": "shop",
                "addFpVideo.shtml": "operation",
                "listFpHdFinancingBlind.shtml": "operation",
                "querySalesPerformance.shtml": "salecon",
                "addBatchSalesPrizes.shtml": "salecon",
                "toDataList.shtml": "behavior",
                "queryCaiWuMyOrderListByGaiZao.shtml": "finance",
                "listFpAccountVoucher.shtml" : "finance",
                "queryBankCard.shtml": "finance",
                "queryAccountWithdraw.shtml": "finance",
                "queryProductQDList.shtml": "product",
                "queryUpdateProjectAnnualRevenue.shtml": "product",
                "addBlacklist.shtml": "product",
                "queryAccountWithdrawDetail.shtml": "product",
                "updateProjectAnnualRevenue.shtml": "product",
                "updateWithdrawStatus.shtml": "operation",
                "addPublicActivitiesPer.shtml": "operation",
                "queryBlacklist.shtml": "fa",
                "deleteProject.shtml": "product",
                "addPublicActivities.shtml": "operation",
                "queryBlacklistDetail.shtml": "fa",
                "addProjectCompany.shtml": "product",
                "changepRecruitmentSummary.shtml": "product",
                "publicActivitiesList.shtml": "operation",
                "productSet.shtml": "product",
                "queryList.shtml": "product",
                "updateProjectCompany.shtml": "product",
                "activitiesNowPerson.shtml": "operation",
                "addFl.shtml": "operation",
                "login.shtml": "common",
                "newsManagePer.shtml": "operation",
                "listProjectCompany.shtml": "product",
                "updateFl.shtml": "operation",
                "queryPublicActivities.shtml": "operation",
                "addNews.shtml": "operation",
                "fileUpload.shtml": "common",
                "loginPer.shtml": "operation",
                "queryProjectCompanyView.shtml": "product",
                "deleteFl.shtml": "operation",
                "listNews.shtml": "operation",
                "updatePublicActivities.shtml": "product",
                "deleteProjectCompany.shtml": "product",
                "fLDetail.shtml": "operation",
                "updateProjectForPublish.shtml": "product",
                "queryProjectAttachments.shtml": "product",
                "queryProjectListForPublishPer.shtml": "product",
                "queryFaUserListPer.shtml": "fa",
                "addAction.shtml": "system",
                "listInfoSubscribe.shtml": "product",
                "addProjectAccount.shtml": "product",
                "queryProjectListForPublish.shtml": "product",
                "queryProjectForPublish.shtml": "product",
                "queryFaUserList.shtml": "fa",
                "updateFaUser.shtml": "fa",
                "queryFaUser.shtml": "fa",
                "queryShopFaUser.shtml": "fa",
                "updateShopFaUserForAudit.shtml": "fa",
                "updateProjectAttachments.shtml": "product",
                "addProjectAnnualRevenuePer.shtml": "product",
                "addActionPer.shtml": "system",
                "addProjectAnnualRevenue.shtml": "product",
                "queryCountInfo.shtml": "operation",
                "queryCompany.shtml": "product",
                "addProjectRisk.shtml": "product",
                "deleteNews.shtml": "operation",
                "queryUpdateProjectRisk.shtml": "product",
                "addGroup.shtml": "system",
                "addProductRecommend.shtml": "product",
                "updateGroupInfo.shtml": "system",
                "queryOrderListPer.shtml": "order",
                "queryProjectListForVerifyPer.shtml": "product",
                "updateADFaUser.shtml": "fa",
                "newsContent.sthml": "operation",
                "queryOrderList.shtml": "order",
                "queryProjectListForVerify.shtml": "product",
                "newsDetail.shtml": "operation",
                "queryOrderDetail.shtml": "order",
                "updateCompany.shtml": "product",
                "fpUserFeedBackList.shtml": "operation",
                "projectAllSubscription.shtml": "product",
                "queryProjectForVerify.shtml": "product",
                "updateOrderStatus.shtml": "order",
                "addCompany.shtml": "product",
                "updateProjectForVerify.shtml": "product",
                "querySwitch.shtml": "system",
                "discussManage.shtml": "product",
                "addProjectPer.shtml": "product",
                "updateProjectRisk.shtml": "product",
                "updateFpUserFeedBack.shtml": "operation",
                "updateSwitch.shtml": "system",
                "projectCommentsManage.shtml": "product",
                "addAdvert.shtml": "operation",
                "index.shtml": "common",
                "error.shtml": "common",
                "queryAdvertList.shtml": "operation",
                "updateNews.shtml": "operation",
                "updateAdvert.shtml": "operation",
                "updateUserInfo.shtml": "system",
                "queryApiSetting.shtml": "operation",
                "logout.shtml": "common",
                "queryAdvertInfo.shtml": "operation",
                "addUser.shtml": "system",
                "productRecommendList.shtml": "product",
                "updateApiSetting.shtml": "operation",
                "updateProjectPer.shtml": "product",
                "addApiSetting.shtml": "operation",
                "queryUpdateProjectList.shtml": "product",
                "queryFaUserVisit.shtml": "fa",
                "queryUpdateProject.shtml": "product",
                "updateProjectBaseInfo.shtml": "product",
                "addProject.shtml": "product",
                "addFaUserVisit.shtml": "fa",
                "queryUpdateProjectAccount.shtml": "product",
                "updateProjectAccount.shtml": "product",
                "queryOrderTmpList.shtml": "order",
                "updateOrderTmp.shtml": "order",
                "queryActivitiesMollionsWealth.shtml": "operation",
                "licaishiManagerUserAdd.shtml": "order",
                "queryQuDaoMyOrderListByGaiZao.shtml": "order",
                "queryQuDaoAllOrderListByGaiZao.shtml": "order",
                "queryCaiWuAllOrderListByGaiZao.shtml": "order",
                "queryChanPinMyOrderListByGaiZao.shtml": "order",
                "queryChanPinAllOrderListByGaiZao.shtml": "order",

                "queryFaUserRegisterByMonthCount.shtml": "statistics",
                "queryFaUserRoleCount.shtml": "statistics",
                "queryFaUserCount.shtml": "statistics",
                "queryOrderCountByMonth.shtml": "statistics",
                "queryOrderUserPer.shtml": "statistics",
                "queryOrderFaUserRoleProportion.shtml": "statistics",
                "queryFaUserRoleProportion.shtml": "statistics",
                "queryUserTotalSales.shtml": "statistics",
                "queryCommpanyTotal.shtml": "statistics",
                "queryProductKeyWord.shtml": "statistics"
            };
            return map[url] || "";
        };

    }]);

angular.module('faApp')
  .service('beService', ['ajaxService', '$http', '$location', '$q', function(ajaxService, $http, $location, $q) {

    this.getDataList = function(cfg) {
      cfg.type = "queryDateList";
      return ajaxService.post(ajaxService.getApiUri("USER_BEHAVIOR_LIST"), cfg || {});
    };
    this.getDateInfo = function(cfg) {
      cfg.type = "queryDateDetail";
      return ajaxService.post(ajaxService.getApiUri("USER_BEHAVIOR_LIST"), cfg || {});
    };

    this.faUserVisit = function(loginName) {
      return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT"), { loginName: loginName });
    };

    this.addRemark = function(visit) {
      return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT_ADD"), visit || {});
    }
  }]);

angular.module('faApp')
  .service('bidProductService', [ 'ajaxService',function (ajaxService) {

    this.bidProductList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("BID_PRODUCT_LIST"),cfg || {});
    };  
    this.bidProductDetail = function(id) {
      return ajaxService.post(ajaxService.getApiUri("BID_PRODUCT_DETAIL"),{id:id})
    }
    this.bidProductStatus = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("BID_PRODUCT_DTATUS"),cfg || {} );
    };

}]);
angular.module('faApp')
  .service('blindateService', ['ajaxService', '$http', '$location', '$q', function(ajaxService, $http, $location, $q) {

    this.getDataList = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("BLINDATE_LIST"), cfg || {});
    };
    this.dateUpdata = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("BLINDATE_UPDATA"), cfg || {});
    };
  }]);

angular.module('faApp')
  .service('caleconService', ['ajaxService', '$http', '$location', '$q', function(ajaxService, $http, $location, $q) {

    this.getDataList = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("USER_SAlECON_LIST"), cfg || {});
    };

  }]);

angular.module('faApp')
  .service('shareService', [ function () { 
    var map = {};
    this.get = function (k,v) {
      return map[k] ? map[k] : v;
    }; 
    this.set = function(k,v){
      map[k] = v;
    };
    this.remove = function(k){
      delete map[k];
    };
  }])
  .service('sessionService', [ function () { 
    this.getItem = function (k,v) {
      return sessionStorage.getItem(k) || v;
    }; 
    this.setItem = function(k,v){
      sessionStorage.setItem(k,v);
    };
    this.removeItem = function(k){
      sessionStorage.removeItem(k);
    };
    this.clear = function(){
      sessionStorage.clear(); 
    };
  }])
  .service('operationService',['ajaxService',function(ajaxService){
    this.statCount = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("OPERATION_STAT_COUNT"),cfg || {}); 
    };
    //我的业绩,团队业绩
    //  /api/order/queryOrderOwnerUserCountAmount.shtml
    this.queryOrderOwnerUserCountAmount = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("queryOrderOwnerUserCountAmount"),cfg || {});
    };
    this.queryVistDetail = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("queryVistDetail"),cfg || {});
    };
    //关注客户
    this.customerFocus = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("customerFocus"),cfg || {});
    };
    this.listFaRevisitTask = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("listFaRevisitTask"),cfg || {});
    };
    this.updateFaRevisitTask = function(cfg){
      return ajaxService.jsonp(ajaxService.getApiUri("updateFaRevisitTask"),cfg || {});
    };


  }])
  .service('exportService', [ 'ajaxService',function (ajaxService) { 
    this.exportCSV = function (cfg,api) {
      cfg.pageSize && (cfg.pageSize = 100000);
      cfg.pageNo && (cfg.pageNo = 1);
      return ajaxService.export(ajaxService.getApiUri(api),cfg || {}); 
      
    }; 
  }])
;
 


angular.module('faApp')
  .service('companyService', [ 'ajaxService',function (ajaxService) {

    this.companyList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("COMPANY_LIST"),cfg || {});
    };  
    
    this.companyAdd = function (item) {
      return ajaxService.post(ajaxService.getApiUri("COMPANY_ADD"),item || {});
    };  

    this.companyEdit = function (item) {
      return ajaxService.post(ajaxService.getApiUri("COMPANY_EDIT"),item || {});
    };  

    this.companyQuery = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("COMPANY_QUERY"),{companyId:id});
    };  

    this.companyDelete = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("COMPANY_DELETE"),{companyId:id});
    };  

    this.subList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("COMPANY_SUB_LIST"),cfg || {});
    };  
}]);
 




angular.module('faApp')
.service('faService', [ 'ajaxService',function (ajaxService) {
  this.faList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_LIST"),cfg || {});
  }; 
  
  this.faQuery = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_QUERY"),cfg || {});
  };
  this.faShopQuery = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_SHOPQUERY"),cfg || {});
  };
  
  this.certQuery = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_QUERY_CERT"),cfg || {});
  };
 
  this.certSave = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_UPDATE_CERT"),cfg || {});
  };

  this.shopCertSave = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_UPDATE_SHOPCERT"),cfg || {});
  };
 
  this.certSaveImg = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_UPDATE_CERTIMG"),cfg || {});
  };
 
  this.blackAdd = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_BLACK_ADD"),cfg || {});
  }; 
 
  this.blackQuery = function (id) {
    return ajaxService.post(ajaxService.getApiUri("FA_BLACK_QUERY"),{userId:id});
  }; 
 
  this.blackList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_BLACK_LIST"),cfg || {});
  }; 
  
  this.sbdstat = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_SBDSTAT"),cfg || {});
  }; 
 
  this.sbddetail = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("FA_SBDLIST"),cfg || {});
  }; 
 
  this.faUserVisit = function (id) {
    return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT"),{faId : id});
  }; 

  this.faUserVisitAdd = function (visit) {
    return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT_ADD"), visit || {});
  }; 
  this.faUserVisitDetailAdd = function (visit) {
    return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT_DETAIL_ADD"), visit || {});
  }; 

  this.faUserVisitUpdate = function (visit) {
    return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT_UPDATE"), visit || {});
  }; 

  this.markFaUser = function (id) {
    return ajaxService.post(ajaxService.getApiUri("FA_MARK_FA_USER"),{companyId : id});
  }; 

  this.sanfangQuery = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("SANFANG_QUERY"), cfg || {});
  };

  this.sanfangUpdate = function (sf) {
    return ajaxService.post(ajaxService.getApiUri("SANFANG_UPDATE"), sf || {});
  };

  this.sanfangAdd = function (sf) {
    return ajaxService.post(ajaxService.getApiUri("SANFANG_ADD"), sf || {});
  };

  this.sanfangDelete = function (id) {
    return ajaxService.post(ajaxService.getApiUri("SANFANG_DELETE"), {tpCompanyId: id} );
  };
  //查询机构
  this.jigouQuery = function(cfg){
    return ajaxService.post(ajaxService.getApiUri("JIGOU_QUERY"), cfg || {});
  }
  this.downLineList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_LIST"), cfg || {} );
  };
  this.downLineDetail = function (id) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_DETAIL"), {id: id} );
  };
  this.downLineAdd = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_ADD"), cfg || {} );
  };
  this.downLineUpdata = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_UPDATA"), cfg || {} );
  };
  this.downLineUpFile = function (path) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_UPFILE"),  {path : path} );
  };
  this.downLineUpFileload = function (path) {
    return ajaxService.post(ajaxService.getApiUri("DOWNLINE_UPFILE_TU"),  {path : path} );
  };

  this.revisiitTask = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("REVISIITTASK"),cfg || {});
  };
  //查询注册来源活动
  this.queryActSource = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("QUERYACTSOURCE"),cfg || {});
  };

//内部理财师汇总数据列表
  this.lcsmanList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("LCS_MAN_STATICTICS_LIST"), cfg || {});
  };
// 查询内部理财师详情列表
  this.lcsmanDetailList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("LCS_MAN_DETAIL_LIST"), cfg || {});
  };
}]);
angular.module('faApp')
.service('financierService', ['ajaxService', function(ajaxService) {

  this.financierList = function(cfg) {
    return ajaxService.post(ajaxService.getApiUri("FINANCIER_LIST"), cfg || {});
  };

  this.financierAdd = function(financier) {
    return ajaxService.post(ajaxService.getApiUri("FINANCIER_ADD"), financier || {});
  };

  this.financierDelete = function(id) {
    return ajaxService.post(ajaxService.getApiUri("FINANCIER_DELETE"), id || {});
  };

}]);
angular.module('faApp')
.service('fissService', [ 'ajaxService',function (ajaxService) {
  this.fissList = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("FISS_LIST"),cfg || {});
  };  
 
}]);




angular.module('faApp')
  .service('folllowUpService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_ORDER_LIST"),cfg || {});
    };
    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_QUERY"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_STATUS"),cfg || {});
    };
    this.queryOrderList=function(){
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_FOLLOW_UP_LIST"));
    }   
   
}]);
 




angular.module('faApp')
  .service('fpAccountVoucherService', [ 'ajaxService',function (ajaxService) {

    this.queryAllExistingAccount = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_ALL_EXISTING_ACCOUNT"),cfg || {});
    };

    this.listFpAccountVoucher = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_FP_ACCOUNT_VOUCHER"),cfg || {});
    };
    
    this.detailFpAccountVoucher = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_FP_ACCOUNT_VOUCHER_DETAIL"),cfg || {});
    };

    this.queryAccountVoucherCreateBy = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_ACCOUNT_VOUCHER_CRAETEBY"),cfg || {});
    };

      this.updateFpAccountVoucher = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_FP_ACCOUNT_VOUCHER_UPDATE"),cfg || {});
    };
       this.addFpAccountVoucher = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_FP_ACCOUNT_VOUCHER_ADD"),cfg || {});
    };

}]);
angular.module('faApp')
.service('hongbaoService', [ 'ajaxService',function (ajaxService) {
  this.hongbaoList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("HONGBAO_LIST"),cfg || {});
  };  

  this.hongbaoDetail = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("HONGBAO_DETAIL"),cfg || {});
  };  
  this.hongbaoJihuo = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("HONGBAO_JIHUO"),cfg || {});
  }; 
}]);


angular.module('faApp')
  .service('infoManageService', [ 'ajaxService',function (ajaxService) {

    this.fbList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_FEED_BACK"),cfg || {});
    };

    this.bcList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_BANK_CARD"),cfg || {});
    };

    this.withdrawList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_WITHDRAW"),cfg || {});
    };
    this.askForList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_ASKFIR_LIST"),cfg || {});
    }; 
    this.askForDetail = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_ASKFIR_DETAIL"),{id : id});
    };
    this.askForFail = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_ASKFIR_FAIL"),cfg || {});
    };
    this.askForSuccess = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_ASKFIR_SUCCESS"),cfg || {});
    };

    this.withdrawDetail = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("INFO_MANAGE_WITHDRAW_DETAIL"),{id:id});
    };
  
    this.withdrawUpdate = function (withdraw) {
      return ajaxService.post(ajaxService.getApiUri("INFO_MANAGE_WITHDRAW_UPDATE"),withdraw || {});
    };
    this.payRunningList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("INFO_MANAGE_PARRINNING_LIST"),cfg || {});
    };
}]);
angular.module('faApp').service('licaishiManagerService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("LICAISHI_MANAGER_USER_LIST"),cfg || {});
    };

    this.otherList = function (cfg) {
        return ajaxService.post(ajaxService.getApiUri("LICAISHI_MANAGER_USER_LIST_OTHER"),cfg || {});
    };

    this.notLicaishiManagerUserList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("NOT_LICAISHI_MANAGER_USER_LIST"),cfg || {});
    };

    this.licaishiManagerUserAdd = function (user) {
      return ajaxService.post(ajaxService.getApiUri("LICAISHI_MANAGER_USER_ADD"),user || {});
    };

    this.managerLicaishiUserAdd = function (manageLicaishi) {
      return ajaxService.post(ajaxService.getApiUri("MANAGER_LICAISHI_USER_ADD"),manageLicaishi || {});
    };

    this.huishouManagerLicaishiByUser = function(cfg){
      return ajaxService.post(ajaxService.getApiUri("MANAGER_LICAISHI_HUISHOU_BY_USER"),cfg || {});
    }
}]);


angular.module('faApp')
  .service('linkService', [ 'ajaxService',function (ajaxService) {

    this.linkList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_LIST"),cfg || {});
    };  
    
    this.linkAdd = function (ad) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_ADD"),ad || {});
    };  

    this.linkEdit = function (ad) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_EDIT"),ad || {});
    };  

    this.linkQuery = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_QUERY") + id + ".shtml");
    };  

    this.linkStart = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_EDIT"),cfg || {});
    };  

    this.linkStop = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_EDIT"),cfg || {});
    };   

    this.linkDelete = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("LINK_DELETE"),cfg || {});
    };  
}]);
 




angular.module('faApp')
    .service('loginService', [ 'ajaxService',function (ajaxService) {

        this.login = function (user) {
            return ajaxService.post(ajaxService.getApiUri("LOGIN"),user);
        };
        //个人修改用户信息
        this.updateLoginInfo = function (user) {
            return ajaxService.post(ajaxService.getApiUri("UPDATELOGININFO"),user);
        };

        this.loginStatus = function (user) {
            return ajaxService.jsonp(ajaxService.getApiUri("LOGIN_STATUS"),user);
        };  

        this.logout = function (user) {
            return ajaxService.jsonp(ajaxService.getApiUri("LOGOUT"),user);
        };  
    }]);
 



angular.module('faApp')
.service('m2bService', [ 'ajaxService',function (ajaxService) {

  this.winList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("M2B_WIN_LIST"),cfg);
  };  

}]);




angular.module('faApp')
  .service('mediaService', [ 'ajaxService',function (ajaxService) {

    this.mediaRecommendList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("MEDIA_RECOMMEND_LIST"), cfg || {});
    };  
    
    this.mediaRecommendAdd = function (obj) {
      return ajaxService.post(ajaxService.getApiUri("MEDIA_RECOMMEND_ADD"), obj || {});
    };

    this.mediaRecommendDelete = function (obj) {
      return ajaxService.post(ajaxService.getApiUri("MEDIA_RECOMMEND_DELETE"), obj || {});
    };
}]);
angular.module('faApp').service('MessageService', [ 'ajaxService',function (ajaxService) {

  this.messageList = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("MESSAGE_MANAGER_LIST"),cfg || {});
  };

  this.messageEdit = function (message) {
    return ajaxService.jsonp(ajaxService.getApiUri("MESSAGE_MANAGER_EDIT"),message || {});
  };
}]);
angular.module('faApp')
  .service('millionService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("MILLION_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("MILLION_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("MILLION_EDIT"),cfg || {});
    };  

    this.remove = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("MILLION_REMOVE"),cfg || {});
    };  

}]);
 




  angular.module('faApp')
  .service('newOrderService', [ 'ajaxService',function (ajaxService) {
  //渠道个人订单集合
this.qdmlist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_QDM_LIST"),cfg || {});
    };

  //渠道所有订单集合
this.qdalist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_QDA_LIST"),cfg || {});
    };

   //产品个人订单集合
this.cpmlist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CPM_LIST"),cfg || {});
    };

   //产品所有订单集合
this.cpalist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CPA_LIST"),cfg || {});
    };  

       //财务所有订单集合
this.cwalist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CWA_LIST"),cfg || {});
    };   

       //财务管理员所有订单集合
this.cwaglylist = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CWA_GLY_LIST"),cfg || {});
    };   


//产品负责人
this.querycpfzr = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_FZR_LIST"),cfg || {});
    };

//订单修改
this.updateOrderStatusAndOther = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CHANGE_BY_STATUS"),cfg || {});
};

//查询订单详情
this.queryOrderXiangqing = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_XIANGQING"),cfg || {});
    };

    //20170731 调用lisu提供的订单详情
this.queryOrderDetail = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_DTAIL"),cfg || {});
    };

//查询合同详情
this.queryOrderContract = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CONTRACT_DETAIL"),cfg || {});
    };

    //查询合同编辑
this.orderContractUpdate = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CONTRACT_EDIT"),cfg || {});
    };

//查询财务订单详情
this.queryCWOrderXiangqing = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_CWA_VIEW"),cfg || {});
    };

    this.listByProId = function (cfg,id) {
      cfg.oProjectId=id;
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_PROID_LIST"),cfg || {});
    }; 
    
    this.query = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_QUERY"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_STATUS"),cfg || {});
    };  
    
    this.updateDefriendStatus = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_DEFRIENDSTATUS"),cfg || {});
    };  
    this.queryOrderList=function(cfg){
      return ajaxService.post(ajaxService.getApiUri("ORDER_FOLLOW_UP_LIST") ,cfg || {});
    } 

}]);
 




angular.module('faApp')
.service('newsService', ['ajaxService', function(ajaxService) {

  this.newsAdd = function(news) {
    return ajaxService.post(ajaxService.getApiUri("NEWS_ADD"), news || {});
  };

  this.newsEdit = function(news) {
    return ajaxService.post(ajaxService.getApiUri("NEWS_EDIT"), news || {});
  };

  this.newsDelete = function(news) {
    return ajaxService.post(ajaxService.getApiUri("NEWS_DELETE"), news || {});
  };

  this.newsList = function(news) {
    return ajaxService.post(ajaxService.getApiUri("NEWS_LIST"), news || {});
  };

}]);
angular.module('faApp')
  .service('orderFollowUpService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_LIST"),cfg || {});
    };  

    this.listByProId = function (cfg,id) {
      cfg.oProjectId=id;
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_PROID_LIST"),cfg || {});
    }; 
    
    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_QUERY"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_STATUS"),cfg || {});
    };  
    
    this.updateDefriendStatus = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_DEFRIENDSTATUS"),cfg || {});
    };  
    
    this.queryOrderList=function(){
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_FOLLOW_UP_LIST"));
    } 

}]);
 




angular.module('faApp').service('orderManagerService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_MANAGER_USER_LIST"),cfg || {});
    };  

    this.notOrderManagerUserList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("NOT_ORDER_MANAGER_USER_LIST"),cfg || {});
    };

    this.orderManagerUserAdd = function (user) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_MANAGER_USER_ADD"),user || {});
    };

    this.managerOrderUserAdd = function (manageOrder) {
      return ajaxService.post(ajaxService.getApiUri("MANAGER_ORDER_USER_ADD"),manageOrder || {});
    };

    this.managerOrderUserUpdate = function (manageOrder) {
      return ajaxService.post(ajaxService.getApiUri("MANAGER_ORDER_USER_UPDATE"),manageOrder || {});
    };

    this.editManagerOrderByUser = function(systemUserId){
      return ajaxService.post(ajaxService.getApiUri("MANAGER_ORDER_UPDATE_BY_USER"),{systemUserId : systemUserId});
    }
}]);


angular.module('faApp')
  .service('orderPhoService', [ 'ajaxService',function (ajaxService) {

    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_PHO_DETAIL"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("UPDATE_ORDER_PHO"),cfg || {});
    }; 

    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ADD_ORDER_PHO"),cfg || {});
    }; 

    this.addPEVC = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ADD_ORDER_PEVC_PHO"),cfg || {});
    }; 
}]);
 





  angular.module('faApp')
  .service('orderService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_LIST"),cfg || {});
    };  
    this.listByProId = function (cfg,id) {
      cfg.oProjectId=id;
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_PROID_LIST"),cfg || {});
    }; 
    
    this.query = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_QUERY"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_STATUS"),cfg || {});
    };  
    
    this.updateDefriendStatus = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("ORDER_EDIT_DEFRIENDSTATUS"),cfg || {});
    };  
    this.queryOrderList=function(cfg){
      return ajaxService.post(ajaxService.getApiUri("ORDER_FOLLOW_UP_LIST") ,cfg || {});
    } 

}]);
 




angular.module('faApp')
  .service('outProductService', [ 'ajaxService',function (ajaxService) {

    this.outProductList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("OUT_PRODUCT_LIST"),cfg || {});
    };  
    this.editOutProduct = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("EDIT_OUT_PRODUCT"),cfg || {});
    };
     this.sendoutProductEmail = function (pids) {
      return ajaxService.post(ajaxService.getApiUri("SEND_OUT_PRODUCT_EMAIL"),{"pids" : pids});
    };
    this.outProductDetail = function (id) {
      return ajaxService.post(ajaxService.getApiUri("OUT_PRODUCT_DETAIL"),{"id" : id});
    };

    this.productRegexList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_REGEX_LIST"),cfg || {});
    };  
     this.editProductRegex = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("EDIT_PRODUCT_REGEX"),cfg || {});
    };

}]);
 




angular.module('faApp')
  .service('personalSupplierService', [ 'ajaxService',function (ajaxService) {

    this.personalSupplierList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PERSONAL_SUPPLIER_LIST"),cfg || {});
    }; 
    this.PersonalSupplierInfo = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PERSONAL_SUPPLIER_INFO"),cfg || {});
    }; 
    this.PersonalSupplierSave = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SAVE_PERSONAL_SUPPLIER"),cfg || {});
    };
    this.PersonalSupplierVisit = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("FA_USER_VISIT"),cfg || {});
    }; 
    this.PersonalSupplierAddVisit = function (visit) {
    return ajaxService.post(ajaxService.getApiUri("FA_USER_VISIT_ADD"), visit || {});
  }; 
}]);
 




angular.module('faApp')
  .service('productService', [ 'ajaxService',function (ajaxService) {

    this.productList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_LIST"),cfg || {});
    };  

    //查询产品公告列表
    this.queryProductNoticeList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("QUERY_PRODUCT_NOTICE_LIST"),cfg || {});
    }; 
     //查询产品公告详情
    this.queryProductNoticeDetail = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("QUERY_PRODUCT_NOTICE_DETAIL"),cfg || {});
    }; 
    //编辑产品公告
    this.editProductNotice = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("EDIT_PRODUCT_NOTICE"),cfg || {});
    }; 

    //查询pe/vc 产品列表
    this.queryProductList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("QUERY_PRODUCT_LIST"),cfg || {});
    }; 
    //查询pe/vc 产品新增
    this.productAddPEVC = function (product,cfg) {
      return ajaxService.post(ajaxService.getApiUri("ADD_PRODUCT_DETAIL"),product || {});
    }; 

    //查询pe/vc 产品编辑
    this.productUpdatePEVC = function (product,cfg) {
      return ajaxService.post(ajaxService.getApiUri("UPDATE_PRODUCT_DETAIL"),product || {});
    }; 
    this.productAdd = function (product,ct) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_ADD"), product || {});
    };  

    this.productEdit = function (product) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_EDIT"),product || {});
    };  

    this.productQuery = function (id) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_QUERY"),{id:id});
    };  

    //渠道查询产品详情
    this.productQdQuery =function (id){
       return ajaxService.post(ajaxService.getApiUri("QD_PRODUCT_QUERY"),{pId:id});
    }

    //产品成立
    this.productEstablish = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_SET"),cfg || {});
    };  

    //下架3  上架2
    this.productStop = function (id,status) {
      return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_PUBLISH"),{id:id,pPublicStatus:status});
    };

    //发布
    this.productPassPublish = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_PUBLISH"),{id:id,status:3,pPublicStatus:2, isFabu: 'true'});
    };

    //审核通过
    this.productPassVerify = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_VERIFY"),{id:id,status:2,pPublicStatus:1});
    };

    //审核拒绝
    this.productDenyVerify = function (id,type) {

     var checkFailReason=prompt("请输入审批备注(可不填)");
        //审核不通过1;拒绝发布2
      if(type == 1){
          return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_VERIFY"),{id:id,status:1,pPublicStatus:4,checkFirstFailReason:checkFailReason});
      }else if(type == 2){
          return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_VERIFY"),{id:id,status:1,pPublicStatus:4,checkFailReason:checkFailReason});
      }

    }; 

    this.updateSaleProcess = function (product) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_UPDATE_SALEPROCESS"),product || {});
    };  

    this.updateRecruitmentProcess = function (product) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_UPDATE_Recruitment"),product || {});
    };  

    this.productRecommend = function (product) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_RECOMMEND"),product || {});
    };    

    this.productDelete = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_DELETE"),{id:id});
    }; 

    this.productProfitList = function (id) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_PROFIT_LIST"),{id:id});
    }; 

    this.productProfitLogList = function (id) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_PROFIT_LOG_LIST"),{pId:id});
    }; 

    this.productProfitUpdate = function (data) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_PROFIT_UPDATE"),data || {});
    }; 

    this.productAttachList = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("PRODUCT_ATTACH_LIST"),{pId:id});
    }; 

    this.productAttachUpdate = function (data) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_ATTACH_UPDATE"),data || {});
    }; 
    
    this.transPermissionAdd = function(data){
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_TRANS_ADD"),data || {});
    }
    
    this.transPermissionList = function(data){
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_TRANS_LIST"),data || {});
    }

    this.sendEmail = function(ids){
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_SEND_EMAIL") , {id:ids})
    }

     this.productQDList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_QUDAO_LIST"),cfg || {});
    }; 

    this.addProductCheckVerify = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_ADD_CHECK"),cfg || {});
    };

      this.productNoticeQuery = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_NOTICE_QUERY"),cfg || {});
      };
      this.productNoticeDelete = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_NOTICE_DELETE"),cfg || {});
      };
      this.proSeriesAdd = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_SERIES_ADD"),cfg || {});
      };
     this.proSeriesList = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_SERIES_LIST"),cfg || {});
      };
      this.proSeriesDelete = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_SERIES_DELETE"),cfg || {});
      };
      this.xcxSearchNoRecordList = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("PRODUCT_SEARCHNO_RECORD_LIST"),cfg || {});
      };

      this.queryAllProductByFullName = function (cfg) {
          return ajaxService.post(ajaxService.getApiUri("QUERY_ALL_PRODUCT_BY_FULLNAME"),cfg || {});
      };
  }]);
 




angular.module('faApp').service('reportService', [ 'ajaxService',function (ajaxService) {

  this.deepAnalyticsDetail = function(pid){
    return ajaxService.jsonp(ajaxService.getApiUri("REPORT_DETAIL"), {fpProductId:pid});
  };

  this.deepAnalyticsSave = function(report){
    return ajaxService.post(ajaxService.getApiUri("REPORT_SAVE"), report || {});
  };
}]);
angular.module('faApp')
  .service('roadVideoService', [ 'ajaxService',function (ajaxService) {

    this.add = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_ADD"), activity || {});
    };

    this.edit = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_EDIT"), activity || {});
    };

    this.list = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_LIST"), activity || {});
    };

    this.detailById = function (id) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_BT_ID"), {id:id});
    };

    this.delete = function (id) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_DELETE"), {id:id});
    };

    this.videoIdbyPro = function (activity) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_PRO_BY_ID"), activity || {});
    };

    this.videoPassword = function (pass) {
      return ajaxService.post(ajaxService.getApiUri("ROADVIDEO_PASSWORD"), {encryptionPassword:pass});
    };

    
}]);
angular.module('faApp')
.service('salesPrizesService', [ 'ajaxService',function (ajaxService) {
  this.salesPrizesList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_SALEPRIZES_LIST"),cfg || {});
  };  
  this.salesPrizesAdd = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_SALEPRIZES_ADD"),cfg || {});
  };  

  this.salesPrizesPeopleAdd = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_SALEPRIZESPEOPLE_ADD"),cfg || {});
  };  
  
  this.salesPrizesPeopleList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_SALEPRIZESPEOPLE_LIST"),cfg || {});
  }; 
  
}]);
angular.module('faApp')
  .service('settingService', [ 'ajaxService',function (ajaxService) {

    this.settingList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("API_SETTING_LIST"), cfg || {});
    };

    this.settingUpdate = function (s) {
      return ajaxService.jsonp(ajaxService.getApiUri("API_SETTING_UPDATE"), s || {});
    };
}]);
angular.module('faApp')
    .service('shopService', ['ajaxService', function (ajaxService) {
        this.shopUserList = function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_USER_LIST"), cfg || {});
        };
        this.shopSucaiList = function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_SUCAI_LIST"), cfg || {});
        };
        this.getBehaviorHomeList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_HOME_LIST"), cfg || {});
        };
        this.getBehaviorProdList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_PROD_LIST"), cfg || {});
        };
        this.getBehaviorCustList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_CUST_LIST"), cfg || {});
        };
        this.getBehaviorFpList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_FP_LIST"), cfg || {});
        };
        this.getBehaviorFooterMenuList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_FOOTERMENU_LIST"), cfg || {});
        };
        this.getShopUserFeedBackList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_USER_FEED_BACK_LIST"), cfg || {});
        };
        this.getShopUserFeedBackADD =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_USER_FEED_BACK_ADD"), cfg || {});
        };
        this.getShopBackGroundList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BACK_GROUND_LIST"), cfg || {});
        };
        this.getShopBackGroundAdd =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BACK_GROUND_ADD"), cfg || {});
        }
        this.getShopSubjectList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_SUBJECT_LIST"), cfg || {});
        };
        this.addShopSubject =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_SUBJECT_ADD"), cfg || {});
        };
        this.updateShopSubject =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_SUBJECT_UPDATE"), cfg || {});
        };
        this.deleteShopSubject =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_SUBJECT_DELETE"), cfg || {});
        };
        this.getCustregisterList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_CUSTREGISTER_LIST"), cfg || {});
        };
        this.getCruxdataList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_BEHAVIOR_CRUXDATA_LIST"), cfg || {});
        };

        this.getShopInformationAdd =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_ADD"), cfg || {});
        };
        this.getShopInformationEdit =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_EDIT"), cfg || {});
        };
        this.getShopInformationDelete =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_DELETE"), cfg || {});
        };
        this.getShopInformationDetail=function (id) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_DETAIL"), {id : id});
        };
        this.getShopInformationList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_LIST"), cfg || {});
        };
        this.upordownInformation =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_INFORMATION_UPORDOWN"), cfg || {});
        };
        this.jcsYxtActivityCount =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YXT_ACTIVITY_COUNT"), cfg || {});
        };
        this.jcsYxtActivityDrawCount =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YXT_ACTIVITY_DRAW"), cfg || {});
        };

        this.pcTotalDynamic =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("PC_TOTAL_DYNAMIC"), cfg || {});
        };
        this.pcTotalDynamicUpdate =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("PC_TOTAL_DYNAMIC_UPDATE"), cfg || {});
        };

        this.playOpenApplyList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("PLAYOPEN_APPLY_LIST"), cfg || {});
        };
        this.playOpenApplyEdit=function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("PLAYOPEN_APPLY_EDIT"), cfg || {});
        };
        this.getShopInfoList =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YYZC_ACTIVITY_SHOPLIST"), cfg || {});
        };
        this.addShopInfo =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YYZC_ACTIVITY_SHOPADD"), cfg || {});
        };
        this.deleteShopInfo =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YYZC_ACTIVITY_SHOPDELETE"), cfg || {});
        };
        this.updateShopInfo =function (cfg) {
            return ajaxService.post(ajaxService.getApiUri("SHOP_YYZC_ACTIVITY_SHOPUPDATE"), cfg || {});
        };



    }]);



angular.module('faApp')
  .service('simuService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };  

    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_QUERY"),cfg);
    };  

    this.remove = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_REMOVE"),cfg || {});
    };  

    this.stop = function (cfg) {
      cfg.pubStatus = '0';
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_EDIT"),cfg);
    };  

    this.start = function (cfg) {
      cfg.pubStatus = '1';
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_EDIT"),cfg);
    };  

    this.queryjjbm = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_QUERY_FUNDCODE"),cfg);
    };  

    this.productRecommend = function (product) {
      return ajaxService.post(ajaxService.getApiUri("PRODUCT_RECOMMEND"),product || {});
    };

}]);
 





angular.module('faApp')
  .service('simuBuyHisService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYHIS_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_BUYHIS_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_BUYHIS_EDIT"),cfg || {});
    };  

    this.query = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYHIS_QUERY"),{id:id});
    };  

    this.remove = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYHIS_REMOVE"),{id:id});
    };  

}]);

angular.module('faApp')
  .service('simuBuyInfoService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYINFO_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_BUYINFO_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_BUYINFO_EDIT"),cfg || {});
    };  
    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYINFO_QUERY"),cfg);
    };  

    this.remove = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_BUYINFO_REMOVE"),cfg || {});
    };  

}]);

angular.module('faApp')
  .service('simuCompanyService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_COMPANY_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_COMPANY_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_COMPANY_EDIT"),cfg || {});
    };  

    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_COMPANY_QUERY"),cfg);
    };  

    this.remove = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_COMPANY_REMOVE"),cfg || {});
    };  

}]);
 





angular.module('faApp')
  .service('simuLsjzService', [ 'ajaxService',function (ajaxService) {
 
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };   

    this.vidioList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_VIDEO_LIST"),cfg || {});
    };  

    this.vidioEdit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_VIDEO_EDIT"),cfg || {});
    };   
  
}]);
 





angular.module('faApp')
  .service('simuLsyjService', [ 'ajaxService',function (ajaxService) {
 
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };   

}]);
 





angular.module('faApp')
  .service('simuManagerService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_MANAGER_LIST"),cfg || {});
    };  
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_MANAGER_ADD"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_MANAGER_EDIT"),cfg || {});
    };  

    this.query = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_MANAGER_QUERY"),cfg);
    };  

    this.remove = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_MANAGER_REMOVE"),cfg || {});
    };  

}]);
 






angular.module('faApp')
  .service('simuNdyjService', [ 'ajaxService',function (ajaxService) {
 
    
    this.add = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };  

    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_EDIT"),cfg || {});
    };   

}]);
 





angular.module('faApp')
  .service('simuOrderService', [ 'ajaxService',function (ajaxService) {

    this.list = function (cfg) {
      cfg.oType = '02';
      return ajaxService.post(ajaxService.getApiUri("SIMU_ORDER_LIST"),cfg || {});
    };  
    this.listByProId = function (cfg,id) {
      cfg.productId=id;
      return ajaxService.jsonp(ajaxService.getApiUri("SIMU_ORDER_PROID_LIST"),cfg || {});
    };  
    
    this.edit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_ORDER_EDIT"),cfg || {});
    };  

    this.query = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("SIMU_ORDER_LIST"),cfg);
    };  
    this.queryOrderList=function(cfg){
      return ajaxService.post(ajaxService.getApiUri("ORDER_FOLLOW_UP_LIST"),cfg || {});
    } 

}]);
 





angular.module('faApp').service('StatisticalService', [ 'ajaxService',function (ajaxService) {

  this.orderList = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("STATISTICAL_ORDER_LIST"),cfg || {});
  };

  this.orderListCsv = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("STATISTICAL_ORDER_LIST_CSV"),cfg || {});
  };

  this.userList = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("STATISTICAL_USER_LIST"),cfg || {});
  };

  this.userListCsv = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("STATISTICAL_USER_LIST_CSV"),cfg || {});
  };
}]);
angular.module('faApp').service('supplierService', [ 'ajaxService',function (ajaxService) {
  this.supplierList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("SUPPLIER_LIST"),cfg || {});
  };
  this.supplierFlowList = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("SUPPLIER_FLOW_LIST"),cfg || {});
  };
  this.supplierDetail = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("SUPPLIER_DETAIL"),cfg || {});
  };
  this.supplierAdd = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("SUPPLIER_ADD"),cfg || {});
  };
  this.supplierEdit = function (cfg) {
    return ajaxService.jsonp(ajaxService.getApiUri("SUPPLIER_EDIT"),cfg || {});
  };
}]);
angular.module('faApp')
  .service('switchService', [ 'ajaxService',function (ajaxService) {

    this.switchList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("SWITCH_LIST"), cfg || {});
    };

    this.switchUpdate = function (s) {
      return ajaxService.jsonp(ajaxService.getApiUri("SWITCH_UPDATE"), s || {});
    };
}]);

angular.module('faApp')
  .service('updateOrderService', [ 'ajaxService',function (ajaxService) {

    this.updateOrderDetail = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_UPDATE_ORDER_EDIT"), cfg || {});
    };  
      
    this.queryOrderDetail = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_UPDATE_ORDER_DETAIL"), cfg || {});
    };  

    this.saveOrderIdList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_UPDATE_ORDER_SAVE"), cfg || {});
    };  

   this.getOrderIdList = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("ORDER_UPDATE_ORDER_QUERY"), cfg || {});
    };  

}]);
angular.module('faApp')
.service('userService', [ 'ajaxService',function (ajaxService) {

  this.userList = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_LIST"),cfg || {});
  };
  this.userListTree = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_LISTTREE"),cfg || {});
  };
  this.userQuery = function (id) {
    return ajaxService.post(ajaxService.getApiUri("USER_QUERY"),{userId : id});
  }; 
  this.userAdd = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_ADD"),cfg || {});
  }; 
  this.userEdit = function (cfg) {
    return ajaxService.post(ajaxService.getApiUri("USER_EDIT"),cfg || {});
  }; 


}]);



angular.module('faApp')
  .service('varietyService', ['ajaxService', '$http', '$location', '$q', function(ajaxService, $http, $location, $q) {

    this.getNewProList = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("EXTERIOR_FETCH__PRO_LIST"), cfg || {});
    };
    this.getNewProInfo = function(id) {
      return ajaxService.post(ajaxService.getApiUri("EXTERIOR_FETCH__PRO_DETAIL"),{id : id});
    };
    this.getSfaProInfo = function(id) {
      return ajaxService.post(ajaxService.getApiUri("SFA__PRO_DETAIL"),{id : id});
    };

    this.giveUpFetchingPro = function(id) {
      return ajaxService.post(ajaxService.getApiUri("GIVEUP_PRO_CAPTURE"), { id: id });
    };

    this.noBindingProList = function(type) {
      return ajaxService.post(ajaxService.getApiUri("NO_BINDING_FETCH__PRO_LIST"), { pType: type });
    }
    this.yesBindingProList = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("YES_BINDING_FETCH__PRO_LIST"), cfg || {});
    }
    this.addBindingPro = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("ADD_BINDING"), cfg || {});
    }
    this.removeBindingPro = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("REMOVE_BINDING"), cfg || {});
    }
    this.updataProInfo = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("UPDATE__PRO_DETAIL"), cfg || {});
    }
    this.addNewPro = function(cfg) {
      return ajaxService.post(ajaxService.getApiUri("ADD_FETCH_PRO"), cfg || {});
    }
  }]);

angular.module('faApp')
  .service('withdrawService', [ 'ajaxService',function (ajaxService) {

    this.withdrawList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("WITHDRAW_LIST"),cfg || {});
    };  
    
    this.bankList = function (cfg) {
      return ajaxService.jsonp(ajaxService.getApiUri("WITHDRAW_ADD"),cfg || {});
    };  

    this.withdrawEdit = function (cfg) {
      return ajaxService.post(ajaxService.getApiUri("WITHDRAW_EDIT"),cfg || {});
    };  

    this.withdrawQuery = function (id) {
      return ajaxService.jsonp(ajaxService.getApiUri("WITHDRAW_QUERY"),{id:id});
    };   
}]);
 





angular.module('faApp')
.directive('scrollIf', function () {
	return function (scope, element, attributes) {
		setTimeout(function () {
			if (scope.$eval(attributes.scrollIf)) {
				var h = (new Date()).getHours();
				element[0].parentElement.scrollTop = h * 50;
			}
		});
	}
})
.directive("passwordVerify", function() {
   return {
      require: "ngModel",
      scope: {
        passwordVerify: '='
      },
      link: function(scope, element, attrs, ctrl) {
        scope.$watch(function() {
            var combined;

            if (scope.passwordVerify || ctrl.$viewValue) {
               combined = scope.passwordVerify + '_' + ctrl.$viewValue; 
            }                    
            return combined;
        }, function(value) {
            if (value) {
                ctrl.$parsers.unshift(function(viewValue) {
                    var origin = scope.passwordVerify;
                    if (origin !== viewValue) {
                        ctrl.$setValidity("passwordVerify", false);
                        return undefined;
                    } else {
                        ctrl.$setValidity("passwordVerify", true);
                        return viewValue;
                    }
                });
            }
        });
     }
   };
}) 
.directive("loadScript", ["$timeout",  function ($timeout ) {
	return {
		replace: true,
		restrict: 'AE',
		link: function (scope, elm, iAttrs) {

			var callBack = scope.$eval(iAttrs.callBack);
			var async = iAttrs.async === false;

			iAttrs.$observe("src", function (src) {
				if (src) {
					scriptTag(scope.$eval(src), function () {
						$timeout(function () {
							callBack && callBack();
						})
					}, async);
				}
			});


			function scriptTag(src, callback, async) {
				var doc = document,
					head = document.getElementsByName("head")[0],
					s = doc.createElement('script');

				s.type = 'text/' + (src.type || 'javascript');
				s.src = src.src || src;
				s.async = async || true;

				s.onreadystatechange = s.onload = function () {

					var state = s.readyState;

					if (!state || /loaded|complete/.test(state)) {
						callback(arguments);
					}
				};

				// use body if available. more safe in IE
				(doc.body || head).appendChild(s);
			};
		}
	};
}])

.directive("navMenu", function() {
  return {
    link: function(scope, element, attrs, ctrl) {
      attrs['module'] = attrs['module'] || "";
    
      scope.$watch('nav', function() {
        if (scope.nav.module == attrs['module']){
          element.removeClass("ng-hide");
        }else{
          element.addClass("ng-hide");
        }
      },true);
    }
  };
})  
.directive("hasAuth", ['sessionService','ajaxService','authService',function(sessionService,ajaxService,authService) {
  return {
    priority:100,
    link: function(scope, element, attrs, ctrl) {
      var who = attrs.who || "",
          where = attrs.where || "";
          owner = attrs.owner || "";
      
      // 权限
      scope._access = sessionService.getItem("user.access","");
      if (scope._access == "all")return;
      try{
        scope.user = angular.fromJson(sessionService.getItem("user",""));
      }catch(ex){
        scope.user = {};
      }
      

      var btnProcess = function(){
        var authFlag = false;
        angular.forEach(who.split(","),function(o){
          var realUrl = ajaxService.getApiUri(o);
          urlPaths = realUrl.split("/"),
          lastUrlPath = urlPaths[urlPaths.length - 1];
        if (scope._access.indexOf(lastUrlPath) != -1){
          authFlag = true 
        }
        });

        var ownerFlag = false;
        if (authFlag){
          if (!owner)ownerFlag = true;
          else{
            if (owner == scope.user.name){
              ownerFlag = true;
            }
          }
        }


        if (!(authFlag && ownerFlag)){
          element.remove();
        }
      };
      
      var topProcess = function(){
      
        var groups = [];
        angular.forEach(scope._access.split(","),function(o){
          var m = authService.getModule(o);
          if (groups.indexOf(m) == -1){
            groups.push(m);
          }    
        });
        if (groups.indexOf(who) == -1){
          element.remove();
        }
      };
      
      var roleProcess = function(){
        var authFlag = false;
        if (who == "PRODUCT_CORE_PRICE"){
        
        }
      
        if (!authFlag){
          element.remove();
        }
      };
      
      if (attrs.owner == undefined){
        if (where == "top"){
          topProcess();
        }else if (where == "btn"){
          btnProcess();
        }else if (where == "role"){
          roleProcess();
        }
      }else{
        attrs.$observe('owner',function(v){
          owner = attrs.owner;
          if (owner){
            if (where == "top"){
              topProcess();
            }else if (where == "btn"){
              btnProcess();
            }else if (where == "role"){
              roleProcess();
            }
          }
        }); 
      }
    }
  };
}]) 
.directive('ngConfirmClick', [
  function(){
    return {
      priority: 1,
      terminal: true,
      restrict: 'A',
      link: function(scope, element, attrs){
        element.bind('click', function(e){
          var message = attrs.ngConfirmClick || "请确认操作";
          if(confirm(message)){
            scope.$eval(attrs.ngClick)
          }else{
            e.stopImmediatePropagation();
            e.preventDefault();
          }
        });
      }
    }
  }
])
.directive('onlyNum', function() {
      return function(scope, element, attrs) {

          element.bind("keypress", function(event) {
            event = (event) ? event : ((window.event) ? window.event : ""); 
            var k = event.keyCode?event.keyCode:event.which;
            if(!((k>=48 && k<= 57) || (k==8) || (k==46))) {
                scope.$apply(function(){
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
     };
  })
.directive('nameInput', function() {//only [0-9],[a-z],[A-Z],中文
      return function(scope, element, attrs) {

          element.bind("keypress", function(event) {
            event = (event) ? event : ((window.event) ? window.event : ""); 
            var k = event.keyCode?event.keyCode:event.which;
            if(!((k>=97 && k<=122) || (k>=65 && k<=90) || (k>=48 && k<= 57) || (k==8))) {
                scope.$apply(function(){
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
     };
  })
.directive('clickAnywhereButHere', function($document){
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      });
      $document.bind('click', function() {
        scope.$apply(attr.clickAnywhereButHere);
      })
    }
  }
})
.directive('eChart', function ($location) {
    function link($scope, element, attrs) {
        var myChart = echarts.init(element[0]);
        $scope.$watch(attrs['eData'], function () {
            var option = $scope.$eval(attrs.eData);
            if (angular.isObject(option)) {
                myChart.setOption(option);

                if(attrs['eEvent'] == 'true'){
                    console.log(attrs['eEvent']);
                    myChart.on('click', function (params) {
                        if(params.name.split(',,,')[0]){
                            window.location = '/fa/view?id=' + params.name.split(',,,')[0];
                        }
                    });
                }
            }
        }, true);
        $scope.getDom = function () {
            return {
                'height': element[0].offsetHeight,
                'width': element[0].offsetWidth
            };
        };
        $scope.$watch($scope.getDom, function () {
            // resize echarts图表
            myChart.resize();
        }, true);
    }
    return {
        restrict: 'A',
        link: link
    };
})
.directive('a', function($document, $timeout){
    return {
        restrict: 'E',
        link: function(scope, elem, attr, ctrl) {
            if(attr.href && attr.href.indexOf('?') > 0){
                $timeout(function(){
                    var param = attr.href.split('?');
                    param[1] = 'token=' + App.randomString(100) + '&' + param[1] + '&' + App.randomString(60);

                    var tmp = param[0] + '?' + param[1];
                    attr.$set('href', tmp);
                }, 50);
            }
        }
    }
})
;


function numberFormat(s,n){
	n = n > 0 && n <= 20 ? n : 2;
	s = App.toFixed(parseFloat((s + "").replace(/[^\d\.-]/g, "")),n) + "";
	var l = s.split(".")[0].split("").reverse(),
		r = s.split(".")[1];
	t = "";
	for(i = 0; i < l.length; i ++ ){
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	} 
	return t.split("").reverse().join("") + (r ? ("." + r) : "");
}
angular.module('faApp')
	.filter('productSaleStatusRender', function() {
		return function(v) {
			var l = App.dictMap['productSaleStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "未知";
		}
	})
	.filter('productPevcSaleStatusRender', function() {
		return function(v) {
			var l = App.dictMap['pevcproductSaleStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "未知";
		}
	})
	.filter('productSupplierStatusRender', function() {
		return function(v) {
			var l = App.dictMap['productSupplierStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "未知";
		}
	})

	.filter('moneyRender', function() {
		return function(v,flag,yuanFlag) {
			v = App.getFloat(v);
			if (flag && v < 1)return "-";
			if (yuanFlag)return numberFormat(v,2) + "元";

			if (v / 100000000 >= 1) return numberFormat(v / 100000000) + "亿元";
			else if (v / 10000 >= 1) return numberFormat(v / 10000) + "万元";
			else return numberFormat(v) + "元";
		}
	})
	.filter('profitRender', function() {
		return function(rate, flag) {

			if(rate==undefined) return "-"
			rate = rate || 0;
			if (flag && rate <= 0) return "-";
			if (rate > 100) rate = 100;
			if (/^[\d.]+$/.test(rate)){
				return (rate || 0) + "%";
			}else{
				return rate;
			}
		}
	})
	.filter('orderStatusRender', function() {
		return function(v) {
			var l = App.dictMap['orderStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('oDefriendStatusRender', function() {
		return function(v) {
			var l = App.dictMap['oDefriendStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('orderNextStatusRender', function() {
		return function(status) {
			var status = status + "",
				text = "";
			if (status == "110" || status == "120" || status == "121" || status == "122" || status == "123" || status == "124"){
				text = "130";
			}else if (status == "130"){
				text = "210";
			}else if (status == "140"){
				return "";
			}else if (status == "210"){
				text = "";
			}else if (status == "220"){
				text = "240";
			}else if (status == "240"){
				text = "";
			}else if (status == "250"){
				text = "320";
			}else if (status == "310" || status == "311" || status == "312" || status == "313"){
				text = "320";
			}else if (status == "314"){
				text = "320";
			}else if (status == "320"){
				text = "";
			}else if (status == "330"){
				text = "";
			}else if (status == "999"){
				text = "";
			}
			return text;
		}
	})
	.filter('orderNextStatusTextRender', function() {
		return function(status) {
			var status = status + "",
				text = "预约已提交，等待结果";
			if (status == "110" || status == "120" || status == "121" || status == "122" || status == "123" || status == "124"){
				text = "预约成功";
			}else if (status == "130"){
				text = "合同已寄出";
			}else if (status == "140"){
				return "交易结束";
			}else if (status == "210"){
				text = "等待打款";
			}else if (status == "220"){
				text = "确认到款";
			}else if (status == "240"){
				text = "等待产品成立";
			}else if (status == "250"){
				text = "确认返佣";
			}else if (status == "310" || status == "311" || status == "312" || status == "313"){
				text = "确认返佣";
			}else if (status == "314"){
				text = "确认返佣";
			}else if (status == "320"){
				text = "等待反佣确认";
			}else if (status == "330"){
				text = "交易结束";
			}else if (status == "999"){
				text = "交易结束";
			}
			return text;
		}
	})
	.filter('processBtnTextRender', function() {
		return function(status) {
			var status = status || 0;
			if (status == "110" || status == "120" || status == "121" || status == "122" || status == "123" || status == "124"){
				return "预约已提交，请等待结果";
			}else if (status == "130"){
				return "预约已成功,请等待合同";
			}else if (status == "140"){
				return "预约失败，返回列表";
			}else if (status == "210"){
				return "下一步:已签约打款";
			}else if (status == "220"){
				return "等待到款确认，返回列表";
			}else if (status == "240"){
				return "等待产品成立，返回列表";
			}else if (status == "250"){
				return "产品已成立，返回列表";
			}else if (status == "310" || status == "311" || status == "312" || status == "313"){
				return "对帐中，返回列表";
			}else if (status == "314"){
				return "已对帐，等待返佣，返回列表";
			}else if (status == "320"){
				return "下一步:确认返佣";
			}else if (status == "330"){
				return "返回列表";
			}else if (status == "999"){
				return "已取消";
			}else{
			}
		}
	})
	.filter('customerFocusType', function() {
		return function(status) {
			var status = status || 0;
			if (status == "110110" ){
				return "店铺首页";
			}else if (status == "110201"){
				return "信托";
			}else if (status == "110202"){
				return "资管";
			}else if (status == "110203"){
				return "PEVC";
			}else if (status == "110204"){
				return "私募";
			}else if (status == "110205"){
				return "基金详情附件";
			}else if (status == "110209"){
				return "自有产品";
			}else if (status == "110300"){
				return "店铺活动列表";
			}else if (status == "110301"){
				return "店铺活动详情";
			}else if (status == "120201"){
				return "私募产品详情页";
			}else if (status == "120202"){
				return "基金产品详情页";
			}else if (status == "120203"){
				return "私募产品详情页附件查看";
			}else if (status == "120204"){
				return "基金产品详情页附件查看";
			}else if (status == "110507"){
				return "金策师私募产品详情页";
			}else if (status == "110508"){
				return "金策师基金产品详情页";
			}else if (status == "110509"){
				return "金策师私募产品详情页附件查看";
			}else if (status == "110510"){
				return "金策师基金产品详情页附件查看";
			}
		}
	})
	.filter('sexRender', function() {
		return function(v) {
			return v == 1 ? "男" : ( v == 2 ? "女" : "保密");
		}
	})
	.filter('taskStatusRender', function() {
		return function(v) {
			return v == 0 ? "已取消" : (v == 1 ? "未完成" : "已完成");
		}
	})
	.filter('scheduleTypeRender', function() {
		return function(v) {
			return v == 1 ? "拜访" : ( v == 2 ? "备忘" : "提醒");
		}
	})
	.filter('commentStatusRender', function() {
		return function(v) {
			return v == 1 ? "未完成" : ( v == 2 ? "已完成" : "其它");
		}
	})
	.filter('certStatusRender', function() {
		return function(v) {
			return v == 1 ? "未认证" : ( v == 2 ? "初级理财师" : ( v == 3 ? "中级理财师" : ( v == 4 ? "高级理财师" : ( v == 9 ? "机构用户" : "其它"))));
		}
	})
	.filter('userLevelRender', function() {
		return function(v) {
			return v < 10 ? "未认证" : ( v < 20 ? "初级理财师" : ( v < 30 ? "中级理财师" : ( v < 40 ? "高级理财师" : "其它")));
		}
	})
	.filter('messageTypeRender', function() {
		return function(v) {
			var m = {"01":"系统公告","02":"交易通知","03":"生日提醒","04":"个人日程","05":"存续付息","06":"活动通知","07":"满期兑付","08":"赎回通知"};
			return m[v] ? m[v] : "其它";
		}
	})
	.filter('certTypeTextRender', function() {
		return function(v) {
			var l = [{"value":"证劵执业资格","code":"01"},{"value":"基金执业资格","code":"02"},{"value":"期货执业资格","code":"03"},{"value":"黄金投资分析师职业资格","code":"04"},{"value":"上海金交所交易员资格","code":"05"},{"value":"理财规划师职业资格","code":"06"},{"value":"保险咨询","code":"07"},{"value":"港股投资咨询","code":"08"},{"value":"美国证券期货执业资格","code":"09"},{"value":"金融理财师职业资格","code":"10"},{"value":"特许金融分析师资格","code":"11"},{"value":"注册国际投资分析师资格","code":"12"}];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.code == v)return o.value;
			}
			return "";
		}
	})
	.filter('tradeTextRender', function() {
		return function(v) {
			var l =  [ { value:"01",text:"基金"}, { value:"02",text:"证劵"}, { value:"03",text:"期货"}, { value:"04",text:"投资"}, { value:"05",text:"银行"}, { value:"06",text:"保险"}, { value:"07",text:"信托"}, { value:"08",text:"担保"}, { value:"09",text:"拍卖"}, { value:"10",text:"典当"}, { value:"11",text:"其他"}, ];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('faCustomerCategory', function() {
		return function(v) {
			var l =  [ { value:"1",text:"潜在客户"}, { value:"2",text:"普通客户"}, { value:"3",text:"合作伙伴"}, { value:"4",text:"重要客户"}, { value:"5",text:"失效客户"}, ];

			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('faCustomerHeat', function() {
		return function(v) {
			var l =  [ { value:"1",text:"A类客户"}, { value:"2",text:"B类客户"}, { value:"3",text:"C类客户"},];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('faCustomerLable', function() {
		return function(v) {
			var l =  [ { value:"1",text:"信托"}, { value:"2",text:"资管"}, { value:"3",text:"PE/VC"},{ value:"4",text:"阳关私募"},{ value:"5",text:"海外保险"},];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('faCustomerKnowledge', function() {
		return function(v) {
			var l =  [ { value:"1",text:"不熟悉"}, { value:"2",text:"一般熟悉"}, { value:"3",text:"非常熟悉"},];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('faCustomerStage', function() {
		return function(v) {
			var l =  [ { value:"1",text:"初步沟通"}, { value:"2",text:"潜在客户跟踪"}, { value:"3",text:"合同执行"},{ value:"4",text:"产品成立"},{ value:"5",text:"合同期满"},];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('dueTimeRender', function() {
		return function(day) {
			return (day || "") + "个月";
		}
	})
	.filter('productLevelRender', function() {
		return function(v) {
			var l =  App.pLevelModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('ageRender', function() {
		return function(v) {
			v = (v|| "0") ;
			return v != "0" ? v : "-";
		}
	})
	.filter('newsTypeRender', function() {
		return function(v) {
			var l =  App.newsTypeMapModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('truncate', function () {
		return function (text, length, end) {
			text = text || "";
			if (isNaN(length)) length = 10;

			if (end === undefined)
				end = "...";

			if (text.length <= length || text.length - end.length <= length) {
				return text;
			}
			else {
				return String(text).substring(0, length-end.length) + end;
			}

		};
	})
	.filter('productTypeRender', function() {
		return function(v) {
			var l = App.productTypeModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('paymentInterestTypeRender', function() {
		return function(v) {
			var l = App.paymentInterestTypeModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('profitTypeRender', function() {
		return function(v) {
			var m = {"01":"固定收益","02":"浮动收益"};
			return m[v] ? m[v] : "其它";
		}
	})
	.filter('investTypeRender', function() {
		return function(v) {
			var l = App.investTypeModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('publicAreaRender', function() {
		return function(v) {
			var l = App.publicAreaModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "全国";
		}
	})
	.filter('to_trusted', ['$sce', function($sce){
		return function(text) {
			return $sce.trustAsHtml(text);
		};
	}])

	.filter('attachmentFileTypeRender', function() {
		return function(v) {
			var l = App.attachmentFileTypeMap;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('advertPositionSizeRender', function() {
		return function(v) {
			var l = App.advertPositionModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.size;
			}
			return "";
		}
	})

	.filter('advertPositionRender', function() {
		return function(v) {
			var l = App.advertPositionModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})


	.filter('productRecommendPositionRender', function() {
		return function(v) {
			var l = App.dictMap['productRecommendModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})

	.filter('advertStatusRender', function() {
		return function(v) {
			var m = {"01":"已上架","02":"已下架"};
			return m[v] ? m[v] : "其它";
		}
	})
	.filter('productPublicStatusRender', function() {
		return function(v) {
			var l = App.productPublicStatusModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('productStatusRender', function() {
		return function(v) {
			var l = App.productStatusModel;
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('pEndEarlyIdentificationRender', function() {
		return function(v) {
			var l = App.dictMap['pEndEarlyIdentification'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('isListRender', function() {
		return function(v) {
			var m = {"01":"是","02":"否"};
			return m[v] ? m[v] : "其它";
		}
	})
	.filter('faStatusRender', function() {
		return function(v) {
			var m = {"01":"正常","02":"禁用","03":"注销","04":"黑名单"};
			return m[v] ? m[v] : "其它";
		}
	})
	.filter('withdrawStatusRender', function() {
		return function(v) {
			var l = App.dictMap['withdrawStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('mediaSourceRender', function() {
		return function(v) {
			var l = App.dictMap['mediaSourceModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('isEqualMyphone',function(){
		return function (v){
			var mphone = v.substr(0, 3) + '****' + v.substr(7);


			return mphone
		}
	})
	.filter('actSourceRender', function() {
		return function(v) {
			var l = App.dictMap['actSourceModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('doNothingRender', function() {
		return function(v) {
			return v;
		}
	})

	.filter('fissInvestTypeRender', function() {
		return function(v) {
			var l = App.dictMap['fissInvestTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})

	.filter('fissInvestTermRender', function() {
		return function(v) {
			var l = App.dictMap['fissInvestermModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('bankTypeRender', function() {
		return function(v) {
			var l = App.dictMap['bankTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('oRebateTypeRender', function() {
		return function(v) {
			if(v == 2){
				return '财务线下结佣';
			}else if(v == 1){
				return '用户自提';
			}else{
				return "";
			}
		}
	})
	.filter('userStatusRender', function() {
		return function(v) {
			var l = App.dictMap['userStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('cgbdColorRender', function() {
		return function(v) {
			var l = {"新进":"xj","增仓":"zc","不变":"bb","减仓":"jc"}
			return l[v] || "";
		}
	})
	.filter('faRoleStatusRender',function() {
		return function(v,r) {
			var m = {"01":"正常","02":"禁用","03":"注销","04":"黑名单"};
			var vv = m[v] ? m[v] : "其它";
			if (vv == "正常"){
				var l = App.dictMap['roleMapModel'];
				for (var i = 0; i < l.length;i++){
					var o = l[i];
					if (o.value == r)return o.text;
				}
			}else{
				return vv;
			}
			return "";
		}
	})
    .filter('faRzStatusRender',function() {
        return function(v,r) {
            var m = {"01":"正常","02":"禁用","03":"注销","04":"黑名单"};
            var vv = m[v] ? m[v] : "其它";
            if (vv == "正常"){
                var l = App.dictMap['rzMapModel'];
                for (var i = 0; i < l.length;i++){
                    var o = l[i];
                    if (o.value == r)return o.text;
                }
            }else{
                return vv;
            }
            return "";
        }
    })
	.filter('simuStatusRender', function() {
		return function(v) {
			var l = App.dictMap['simuStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('urlPrefixRender', function() {
		return function(v) {
			v = v || "";
			if (v.substring(0,7) == "http://"){
				return v;
			}else{
				return App.staticHost + v;
			}
		}
	})
	.filter('simuOrderStatusRender', function() {
		return function(v) {
			var l = App.dictMap['simuOrderStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('millionStatusRender', function() {
		return function(v) {
			var l = App.dictMap['millionStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('millionTypeRender', function() {
		return function(v) {
			var l = App.dictMap['millionTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('pSizeRatioTypeRender', function() {
		return function(v) {
			var l = App.dictMap['pSizeRatioTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('orderDefriendStatusRender', function() {
		return function(v) {
			var l = App.dictMap['orderDefriendStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "有效";
		}
	})
	.filter('activitiesCodeRender', function() {
		return function(v) {
			var l = App.dictMap['activitiesCodeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('m2bWinTypeRender', function() {
		return function(v) {
			var l = App.dictMap['m2bWinTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('adMsgTypeRender', function() {
		return function(v) {
			var l = App.dictMap['adMsgTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return o.value;
		}
	})
	.filter('switchRender', function() {
		return function(v) {
			var l = App.dictMap['switchModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return o.value;
		}
	})
	.filter('activitiesStatusRender', function() {
		return function(v) {
			var l = App.dictMap['activitiesStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return o.value;
		}
	})
	.filter('messageSortRender', function() {
		return function(v) {
			var l = App.dictMap['messageSortModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return o.value;
		}
	})
	.filter('tjzlView', function() {
		return function(v) {
			var	text = "";
			if (v == "01"||v=="1"){
				text = "身份证正面";
			}else if (v == "02"||v == "2"){
				text = "身份证反面";
			}else if (v == "03"||v == "3"){
				return "银行卡";
			}else if (v == "04"||v == "4"){
				text = "打款凭条";
			}else if (v == "05"||v == "5"){
				return "签字页";
			}else if (v == "06"||v == "6"){
				text = "合同封面";
			}else if (v == "07"||v == "7"){
				return "手持签字页与合同封面照";
			}else if (v == "08"||v == "8"){
				text = "其它";
			}
			return text;
		}
	})
	.filter('oPhoStatusView', function() {
		return function(v) {
			var	text = "未提交审核";
			if (v == "01" ){
				text = "未提交审核";
			}else if (v == "02"){
				return "审核中";
			}else if (v == "03"){
				text = "审核通过";
			}else if(v=="04"){
				text="退回";
			}
			return text;
		}
	})
	.filter('tjzlStatus', function() {
		return function(v) {
			if(v==undefined)return "";
			var	text = v.replace("1","  三件套  ").
			replace("5","  签字页  ").replace("6","  合同封面  ").
			replace("6","  合同封面  ").replace("7","  手持签字页与合同封面照  ").replace("8","  其它  ");
			return text;
		}
	})

	.filter('p2oTypefilter',function(){
		return function(v) {
			if(v==undefined)return "";
			var str=v;
			if(str=='02'){
				str="01";
			}else if(str=='03'){
				str="02";
			}
			return str;
		}
	})
	.filter('pevczzxsRender',function(){
		return function(v) {
			if(v==undefined)return "";
			var str=v;
			if(str=='01'){
				str="信托";
			}else if(str=='02'){
				str="券商资管";
			}else if(str=='03'){
				str="有限合伙";
			}else if(str=='04'){
				str="契约型基金";
			}else if(str=='05'){
				str="基金子公司";
			}else if(str=='06'){
				str="其他";
			}
			return str;
		}
	})
	.filter('oPhoStatusShow',function(){
		return function(v) {
			if(v==undefined)return true;
			var str=false;
			if(v=='03'||v=='02'){
				str=false;
			}else{
				str=true;
			}
			return str;
		}
	})
	.filter('oKnotTypeRender', function() {
		return function(v) {
			var l = App.dictMap['knotTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return "";
		}
	})
	.filter('bankcardShow',function(){
		return function(v) {
			if(v==undefined)return "";
			var str="";
			if(/^(\d{16}|\d{19})$/.test(v) ){
				str=v;
			}else{
				str="";
			}
		}
	})
	.filter('noticeStatus',function(){
		return function(v) {
			if(v==undefined)return v;
			var str="";
			if(v=='1'){
				str="未审核";
			}else{
				str="已审核";
			}
			return str;
		}
	})
	.filter('checkStatusRender',function(){
		return function(v) {
			if(v==undefined)return '';
			var str='';
			if(v=='0'){//审核状态 0待审核,1审核中,2审核通过,3审核不通过,4产品发布,5产品成立，6产品发布失败
				str="待审核";
			}else if(v=='1'){
				str="审核中";
			}else if(v=='2'){
				str="审核通过";
			}else if(v=='3'){
				str="不合格";
			}else if(v=='4'){
				str="产品发布";
			}else if(v=='5'){
				str="产品成立";
			}else if(v=='6'){
				str="产品发布失败";
			}
			return str;
		}
	})
	.filter('moneyRender2', function() {
		return function(v,flag,yuanFlag) {
			if(v==undefined) return "-"

			v = App.getFloat(v);
			if(v==undefined) return "-"
			if(v < 0) return  v +"元"
			if(v==0.00 )return "0元";

			if (yuanFlag)return numberFormat(v,2) + "元";

			if (v / 100000000 >= 1) return numberFormat(v / 100000000) + "亿元";
			else if (v / 10000 >= 1) return numberFormat(v / 10000) + "万元";
			else return numberFormat(v) + "元";
		}
	})
	.filter('profitRender2', function() {
		return function(rate, flag) {
			if(rate==undefined) return "-"
			rate = rate || 0;
			if (flag && rate <= 0) return "-";
			if (rate > 100) rate = 100;
			if (/^[\d.]+$/.test(rate)){
				return (rate || 0) + "%";
			}else{
				return rate;
			}
		}
	})
	.filter('onlineStatus',function(){
		return function(v) {
			if(v==undefined)return v;
			var str="";
			if(v=='1'){
				str="未发布";
			}else{
				str='已发布';
			}
			return str;
		}
	})
	.filter('customerCategoryRender', function() {
		return function(v) {
			if(v == null){
				return "未分类客户";
			}
			var l = App.dictMap['customerCategoryModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('customerClickBtnType', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['customerClickBtnModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})

	.filter('fpGroupStatusRenter', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['fpGroupStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('hadGetGiftRenter', function() {
		return function(v) {
			if(v == null){
				return "否";
			}
			if(v){
				return "是";
			}
			return "否";
		}
	})
	.filter('fpGroupSendAmountStatusRenter', function() {
		return function(v) {
			if(v == null){
				return "否";
			}
			if(v==2){
				return "是";
			}
			return "否";
		}
	})
	.filter('bidMarginRenter', function() {
		return function(v) {
			if(v == 2){
				return "否";
			}
			if(v == 1){
				return "是";
			}
			return "否";
		}
	})
	.filter('biddingStatusModelRenter', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['biddingStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('recommentTypeModelRenter', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['recommentTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('payStatusModelRenter', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['payStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('operateTypeModelRenter', function() {
		return function(v) {
			if(v == null){
				return "其他";
			}
			var l = App.dictMap['operateTypeModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return v;
		}
	})
	.filter('payStatusRenter', function() {
		return function(v) {
			var	text = "";
			if (v == "2"){
				text = "支付成功";
			}else if (v == "3"){
				text = "支付失败";
			}else if (v == "0"){
				return "待支付";
			}
			return text;
		}
	})
	.filter('fetchStatusRenter',function() {
		return function(v){
			if(v == '01'){
				return '保证金';
			}else if(v == '02'){
				return '佣金';
			}else{
				return '其他';
			}
		}
	})
	.filter('oYouDanReceiverRenter',function() {
		return function(v){
			if(v){
				return '已支付';
			}else{
				return '未支付';
			}
		}
	})
	.filter('rebateTypeFilter',function() {
		return function(v){
			if(v==''||v==undefined){
				return "-";
			}
			if(v==1){
				return '按投资金额返佣';
			}else{
				return '按固定费率返佣';
			}
		}
	})
	.filter('ratefilter',function() {
		return function(v){
			if(v==''||v==undefined)
				return "-";
			if(/^.*%$/.test(v) ){
				return v;
			}else{
				return v+"%";
			}
		}
	})
	.filter('bailAmountRender',function() {
		return function(v){
			if(v==0)
				return "---";
			return v+"元";
		}
	})

	.filter('activityProductStatusRender', function() {
		return function(v) {
			var m = {"01":"上架","02":"下架"};
			return m[v] ? m[v] : v;
		}
	})
	.filter('newsSendType', function() {
		return function(v) {
			var m = {"01":"及时推送","02":"定时推送"};
			return m[v] ? m[v] : v;
		}
	})
	.filter('newsStatusRender', function() {
		return function(v) {
			var l = App.dictMap['newsStatusModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v) return o.text;
			}
			return v;
		}
	})
	.filter('webNameFilter',function() {
		return function(v){
			if(v=='1caifu')
				return "壹财富";
			return v;
		}
	})
	.filter('pageTypeFilter',function() {
		return function(v){
			if(v=='trust')
				return "信托";
			else if(v=='assetManagement')
				return "资管";
			return v;
		}
	})
	.filter('CompanyReFilter',function() {
		return function(v){
			if(v == '1'){
				return "线下渠道";
			} else {
				return "线上渠道";
			}
		}
	})
	.filter('regiterseFilter',function() {
		return function(v){
			if(v == '1'){
				return "是";
			} else {
				return "否";
			}
		}
	})
.filter('blindateUserSexFilter',function() {
	return function(v) {
		var l = App.dictMap['blindateUserSexModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('dynamicStateFilter',function() {
	return function(v) {
		var l = App.dictMap['dynamicStateModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('blindateSourceFilter',function() {
	return function(v) {
		var l = App.dictMap['blindateSourceModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('pBelongAreaRender',function(){
	return function(v){
		var l = App.dictMap['pbelongAreaModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('filterFee',function(){
	return function(v){
		if(v == undefined || v == ''){
        return "-";
    }
    if(/^[\d.]+$/.test(v)){
      return v+"%";
    }else{
      return v;

    }
	}
})
.filter('orderListTitleRender',function() {
	return function(v) {
		var l = App.dictMap['orderListTitleModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('contractStatusRender',function() {
	return function(v) {
		var l = App.dictMap['contractStatusModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		if(v=='')return "待申请";
		return v;
	}
})
.filter('contractStatusMKRender',function() {
	return function(v) {
		var l = App.dictMap['contractStatusMKModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		if(v=='')return "申请";
		return v;
	}
})
.filter('orderStatusToNameRender',function() {
	return function(v) {
		var l = App.dictMap['orderStatusToNameModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}
		return v;
	}
})
.filter('costTypeRender',function() {
	return function(v) {
		var s = App.dictMap['costTypeFrontModel'];
		for (var i = 0; i < s.length; i++) {
			var o = s[i];
			if (o.value == v) return o.text;
		}
		var l = App.dictMap['costTypeModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return o.text;
		}

		return v;
	}
})
.filter('flagCostTypeRender',function() {
	return function(v) {
		var l = App.dictMap['costTypeModel'];
		for (var i = 0; i < l.length; i++) {
			var o = l[i];
			if (o.value == v) return true;
		}
		return false;
	}
})
.filter('createByFilterByRender',function() {
	return function(v) {
		if(/^[\d.]+$/.test(v)){
			return "客户";
		}
		return v;
	}
})
	.filter('shopUserRzStatus',function() {
		return function(v) {

			var l = App.dictMap['rzMapModel'];
			for (var i = 0; i < l.length;i++){
				var o = l[i];
				if (o.value == v)return o.text;
			}
			return '未提交认证';
		}
	})

	.filter('answeNum',function() {
		return function(v) {

			if(v==1) {
				return 'A';
			} else if(v==2) {
				return 'B';
			} else if(v==3) {
				return 'C';
			} else if(v==4) {
				return 'D';
			} else if(v==5) {
				return 'E';
			} else if(v==6) {
				return 'F';
			} else if(v==7) {
				return 'G';
			} else if(v==8) {
				return 'H';
			} else if(v==9) {
				return 'I';
			} else if(v==10) {
				return 'J';
			} else if(v==11) {
				return 'K';
			} else if(v==12) {
				return 'L';
			} else if(v==13) {
				return 'M';
			} else if(v==14) {
				return 'N';
			} else if(v==15) {
				return 'O';
			} else if(v==16) {
				return 'P';
			} else if(v==17) {
				return 'Q';
			} else if(v==18) {
				return 'R';
			} else if(v==19) {
				return 'S';
			} else if(v==20) {
				return 'T';
			} else if(v==21) {
				return 'U';
			} else if(v==22) {
				return 'V';
			} else if(v==23) {
				return 'W';
			} else if(v==24) {
				return 'X';
			} else if(v==25) {
				return 'Y';
			} else if(v==26) {
				return 'Z';
			}
			return '';
		}
	})
    .filter('informationTime',function() {
        return function(v) {
            var date = new Date(v);
            var curdate = new Date();
            if(date.getTime() <= curdate.getTime()){
                return date
            }
            return '';
        }
    })
   .filter('prizesTypeFilter',function($filter) {
        return function(v) {
            if(v=='1') {
							return "一等奖";
						} else if(v=='2') {
							return "二等奖";
						} else if(v=='3') {
							return "三等奖";
						} else if(v=='4') {
							return "四等奖";
						} else if(v=='5') {
							return "五等奖";
						}else{
            	return '';
						}
        }
    })
    .filter('hiddenFirst',function($filter) {
        return function(v) {
            if(v==''||v==undefined) {
							return "";
						}else{
							return v.slice(0,1)+"**";
						}
        }
    })
    .filter('hiddenMobile',function($filter) {
        return function(v) {
            if(v==''||v==undefined) {
							return "";
						}else{
							return v.slice(0,3)+"****"+v.slice(7,11);
						}
        }
    })


    .filter('toSplitProductName', ['$sce', function($sce){ 

    		return function(text) { var reg=new RegExp(",","g");    return $sce.trustAsHtml(text.replace(reg,'<br/>')); }; 
   	}]);

;

